Skip to content

JSON Web Token (JWT)

Nikita Bulai edited this page Nov 24, 2016 · 5 revisions

If you wanna use JSON Web Tokens as a value for your Access Tokens, than you need to implement your custom Token Generator. First of all add jwt gem to your Gemfile:

gem 'jwt'

If will do the main work for us in accordance to RFC 7519 standard. Now define custom token generator class:

class JWTGenerator
  HMAC_SECRET = '1d62ada3461$a091c38c95c!0388c8a1a2'.freeze

  # `payload` is a model attributes hash (in case of using some ORM)
  #
  def self.generate(payload = {}, options = {})
    JWT.encode(payload, HMAC_SECRET, 'HS256')

    # You can provide custom secrets if you need:
    #   JWT.encode(payload, options[:secret], 'HS256')
    #
    # or skip any encrypting at all:
    #   JWT.encode(payload, nil, 'none')
    #
    # @see https://github.com/jwt/ruby-jwt for more examples
  end
end

And set it as a token generator class in the GrapeOAuth2 config:

GrapeOAuth2.configure do |config|
  # ...

  config.token_generator_class_name = 'JWTGenerator'
end

That's all!

Clone this wiki locally