Autogenerating ApiKeys?

In the ApiKey authentication documentation, it mentions that ApiKey records are automatically created for new users. This isn’t happening for me. Are they created in CreateUserAuth?

Here is our AppHost configuration:

   //Tell ServiceStack you want to persist User Info in the registered RDBMS
        container.Register<IUserAuthRepository>(c =>
            new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())
            {
                UseDistinctRoleTables = false
            });

        Plugins.Add(new AuthFeature(() => new CustomUserSession(),
            new IAuthProvider[] {
                new CustomCredentialsAuthProvider(),
                new ApiKeyAuthProvider() {
                    RequireSecureConnection = false
                }
            },
            htmlRedirect: "~/"
        ));

Moreover, when browsing the source code in GitHub, I can’t find where this actually happens. Is the documentation incorrect? We are using 4.5.0. Can anyone point me in the right direction?

The API Key AuthProvider uses a Custom AuthEvent to generate new API Keys when a new User is Registered:

internal class ApiKeyAuthEvents : AuthEvents
{
    private readonly ApiKeyAuthProvider apiKeyProvider;

    public ApiKeyAuthEvents(ApiKeyAuthProvider apiKeyProvider)
    {
        this.apiKeyProvider = apiKeyProvider;
    }

    public override void OnRegistered(IRequest httpReq, IAuthSession session, IServiceBase registrationService)
    {
        var apiKeys = apiKeyProvider.GenerateNewApiKeys(session.UserAuthId);
        var authRepo = (IManageApiKeys)HostContext.AppHost.GetAuthRepository(httpReq);
        using (authRepo as IDisposable)
        {
            authRepo.StoreAll(apiKeys);
        }
    }
}

Thanks. Is there anything I need to do to enable this besides enabling the Registration feature? When I register a new user:

http://localhost/portal/api/register?username=uname&email=uname@email.com&password=test&authsecret=secretz&format=json

The UserAuth record is created but no ApiKey.

You’d need to register a supported Auth Repository but otherwise Registering a new User should generate the API Keys.

Helps if the db user has insert permissions on the ApiKey table :grin: . It’s working now. Thanks for your help.

1 Like

I wonder why this only works when you use the RegisterService or the Post as in the sample.

I have a service where I want to create a new user as well.

var authUser = AuthRepository.CreateUserAuth(new UserAuth() { UserName = request.Name }, safeGuid);

For some reasons this is not triggering the AuthEvents on the AuthFeature.

My solution, for now, is to Register the ApiKeyAuthProvider and then generate the keys myself:

var apiKeys = ApiKeyAuthProvider.GenerateNewApiKeys(authUser.Id.ToString());
var authRepo = (IManageApiKeys)HostContext.AppHost.GetAuthRepository(Request);
authRepo.StoreAll(apiKeys);

But something tells me this is not the correct way. Any feedback?

CreateUserAuth() is just an API on the IAuthRepository, a clean API abstraction used by the AuthFeature to persisting users in data stores, it doesn’t itself have any knowledge or coupling to either the AuthFeature, current HTTP Request, etc. Auth Filters themselves are only executed within the context of an Auth Request.

There’s an example of creating users with API Keys at the bottom of the API Key docs.

Ok thanks. So basically that’s what I already was doing - seems to be OK than to do it this way.