开发者

Developing a Service with API Keys (starting point)

Looked on google and couldn't find anything.

Any good resources to开发者_JS百科 get started designing my backend for a RESTless webapp thats going to rely heavily on API keys.

I know how to write restless webservices etc, just never used API-keys. Generally do people just generate guids for users etc?


Here's how I'm creating API keys for a web service:

string CreateApiKey(int length)
{
    var bytes = new byte[length * 2];   
    using (var rng = new RNGCryptoServiceProvider()) 
        rng.GetBytes(bytes);
    var chars = Convert.ToBase64String(bytes)
        .Where(char.IsLetterOrDigit)
        .Take(length)
        .ToArray();
    var key = new String(chars);
    return key;
}


GUID's are typically not "random" enough and can be easily guessed by the bad-guys.

Take some "random" data like the user's password hash, some random numbers and run the result through sha1 or a similar hash function.

If you want one API key per account, simply add it to the account metadata table. Otherwise use a table linked to the accountIds to store the api keys.

Server side use a cache using the api-key as the key to store temporarily the account metadata so you only need to go to the db once per session.

And of course everything must go over https to avoid that the API key be stolen.

Now if your service is "session" oriented you can consider using a temporary session key so you do not need to expose the API key. Look for public key encryption to investigate this further.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜