Rails apiSort Order

Rails API: Devise and JWT Integration Part 1 - [040]

We need to make sure that our Json Web Token solution works with our existing authentication library devise. In this episode we will begin implementing a custom devise strategy that will handle JWT authentication.

Custom Devise Strategy

We need to create a file in config/initializers/jwt_authenticatable.rb

module Devise  module Strategies    class JWTAuthenticatable < Base      def authenticate!        token = get_token        return fail(:invalid) unless token.present?                payload = get_payload        return fail(:invalid) if payload == :expired                resource = mapping.to.find(payload['user_id'])        return fail(:not_found_in_database) unless resource                success! resource      end            private            def get_payload        JWT.decode(          get_token,          Rails.application.secrets.secret_key_base,          true,          { algorithm: 'HS256' }        ).first      rescue JWT::ExpiredSignature        :expired      end            def get_token        auth_header.present? && auth_header.split(' ').last      end            def auth_header        request.headers['Authorization']      end    end  endend

That's it for this episode, next up we'll need to integrate our custom devise strategy and make devise aware of it.