Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate API Key?

Use Case

I'm building an iPhone app with a simple signup and login.

When a user signs up/logs in, I want the Ruby (Sinatra) server to generate/fetch and return an access token for that user that the iPhone client can then send with every subsequent request using Basic Authentication over HTTPS.

I'm not yet implementing OAuth 2.0 so that third party apps can access the server. Right now, I'm just building a simple, internal API (for my own, first-party, iPhone app).

Example

Basically, I want to generate a secret API key like Stripe's: https://manage.stripe.com/account/apikeys

For example: sk_test_NMss5Xyp42TnLD9tW9vANWMr

What's the best way to do that, say in Ruby?

like image 456
ma11hew28 Avatar asked Sep 20 '13 16:09

ma11hew28


People also ask

Can I get API key for free?

How does the API key work? The API is available for developers that have a free Google Maps API key. Usage of the API is not strictly free, but they do offer $200 of free monthly usage for most users. The pricing scales to fit your particular needs and you are only charged for your API usage.

Is it safe to create an API key?

So instead of storing the key in plain text (bad) or encrypting it, we should store it as a hashed value within our database. A hashed value means that even if someone gains unauthorised access to our database, no API keys are leaked and it's all safe.

Is UUID sufficient for API key?

If we're talking about an API key, then the issue isn't collision and there's no relationship with hashing or uuids except the recommended final length. A key should be a random 128-bit string (or 192, or 256 if you need additional security).


1 Answers

The Ruby stdlib provides an entire class of secure random data generators called SecureRandom. Whatever you want, you can probably find it there.

Stripe's keys are essentially URL-safe Base64. You can get something very similar like so:

require 'securerandom'

p "sk_test_" + SecureRandom.urlsafe_base64

(Stripe does strip out non-alphanumeric characters, but that's trivial to do with gsub if you don't want hyphens in your keys.)

like image 188
colinm Avatar answered Nov 02 '22 21:11

colinm