2

E.g. API_key: 4faa86aa5848207502000002 and API_secret 7375d7d1e89d3d602b184432fbcf3c09c7cb30676f19af9ac57d228be401.

Should I use SecureRandom?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CamelCamelCamel
  • 5,200
  • 8
  • 61
  • 93

1 Answers1

11

ActiveSupport::SecureRandom would work for the actual generation, but you should also consider a way to invalidate and reset the token on different events.

Since you're using Devise, take a look at the Token Auth Strategy. You could write a similar strategy with two tokens (API Key and API Secret, respectively). You need to write both the strategy and the Model, but in both cases the Token Auth example gets you pretty far.

As a starting point (from the Token Auth example), your model should declare both required parameters.

module Devise
  module Models
    module APIKeyAuthenticatable
      ...
      def self.required_fields(klass)
        [:api_key, :api_secret]
      end

      def reset_keys
        self.api_key = self.class.api_key
        self.api_secret = self.class.api_secret
      end

You might also want to read Custom authentication strategy for devise. If you're looking to provide a more full-featured API auth solution atop devise devise_oauth2_providable looks pretty good.

Community
  • 1
  • 1
arbales
  • 5,466
  • 4
  • 33
  • 40