API Key - What info to store in database and how to handle

Hi, i have a servicestack API and i want to have a API Key verification.
I want only users with a API key to be able to call my API.

What is best practice for storing this keys, i mean what info of the user should i store in the database.

I was thinking of storing the following column

UserName Varchar(Max)
API Key UniqueIdentifier
AllowedIPAdress Varchar(Max)
ValidTo DateTime

I have tried to read the topic about this but couldn’t really understand what info to store.
Or do you have any other best practice solution for this?

I have implemeted the ApiKeyRequestFilter to verify the key as follorws (not complete)

  public void Verify(IRequest req, IResponse res, object dto)
    {
        if (req.PathInfo.StartsWith("/resource") || req.PathInfo.StartsWith("/postman") ||
            req.PathInfo.StartsWith("/metadata"))
            return;

        var apiKey = req.Headers["x-api-key"];
        if (!IsValid(apiKey))
        {
            throw HttpError.Unauthorized("Unauthorized, invalid API Key");
        }
    }

    private bool IsValid(string apiKey)
    {
        //if (apiKey == null ||
        // The api key is no secret, verify that the key comes from the right referrer url

        

        //using (var conn = _db.OpenConnection())
        //{
        //   return conn.Scalar<bool>("exec is_valid_apikey @apikey", new {apikey = apiKey});
        //}
        return true; //apiKey == "somelongrandomkey";
    }

Have you considered using ServiceStack’s built-in API Key Auth Provider? It enables registering an Auth Provider that protects your Services using an API Key and works out of the box with the most popular Auth Repositories. Essentially it generates an API Key for every user that’s registered which they can use instead of their password to authenticate with ServiceStack. We also have a handy script if you want to generate API Keys for existing users. The API Key Auth Provider assumes you’re storing your users inside one of ServiceStack’s Auth Repository.

But if you want to roll your own, this is the ApiKey class we’re using to store the API Keys for each user and if it helps the ApiKeyAuthProvider.cs contains most of our API Key Auth Provider implementation.

Hi @mythz, Thx for your reply!
I just have a few questions about the API Key Auth Provider.

The persons using the API still needs to login with my MyCredentialsAuthProvider as i use their loginname as some lookup for my queries.

What i want to use is that all calls to the API should have a API key to be able to use the API. The API key should be verified for each call to the API.

Should i still use your API Key Auth Provider? As what i understand this is to be used if you want to skip the normal authentication?

Thx in advance!

The API Key Auth Provider provides an alternative way to authenticate for existing users. It still populates the Users Session so you can still access their UserName but it assumes you’re using the Auth Repository to store the Users Info, if you’re not then it wont be suitable for your use-case.

Thx! I will test it to see how it works. A stupid quqestion, i need to create the database table for the APIKey with it’s columns to be able to get this to work?

Any missing tables are created when you call IAuthRepository.InitSchema(), e.g:

container.Register<IDbConnectionFactory>(c =>
    new OrmLiteConnectionFactory(connString, SqlServer2012Dialect.Provider));

container.Register<IAuthRepository>(c =>
    new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

container.Resolve<IAuthRepository>().InitSchema();

It’s safe to always call this in your AppHost as it’s just ignored if you already have the tables created or you’re using an Auth Repository that doesn’t require tables.

The ApiKey table specifically is automatically created when registering a ApiKeyAuthProvider which defaults to InitSchema=true which will call InitApiKeySchema() on the registered User Auth Repo.

Thx!

I don’t know if i’m doing anything wrong but i get and error.

I have my own AspNetMembershipProvider (connected to my old webforms membership user tables).

Is that causing any problems?

You need to have registered an Auth Repository which is where your User Auth info needs to be persisted in. If you’re using your own Custom Auth Provider you wont be using an Auth Repo which is needed in order to be able to use the API Key Auth Provider.

Thx @mythz,

i will create my own database table and handle it by myself.
Very nice support from your side!

1 Like

InitApiKeySchema() is not getting called automatically. I have to manually call it. I am using v5.2