Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在API模式下在Rails应用程序中实现JWT身份验证_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何在API模式下在Rails应用程序中实现JWT身份验证

Ruby on rails 如何在API模式下在Rails应用程序中实现JWT身份验证,ruby-on-rails,Ruby On Rails,我有一个处于API模式的Rails应用程序 有没有提供简单JWT认证的gem?是的,标准JWT gem很棒。只需将其添加到您的文件: gem 'jwt' 然后我将其作为关注点,我可以包括: module JWTAuthenticatable extend ActiveSupport::Concern included do before_action :authenticate_and_restrict_access, if: -> { %w[json csv].in

我有一个处于API模式的Rails应用程序


有没有提供简单JWT认证的gem?

是的,标准JWT gem很棒。只需将其添加到您的文件:

gem 'jwt'
然后我将其作为关注点,我可以包括:

module JWTAuthenticatable
  extend ActiveSupport::Concern

  included do

    before_action :authenticate_and_restrict_access, if: -> { %w[json csv].include? request.format }

    rescue_from JWT::DecodeError,                   with: :invalid_token
    rescue_from JWT::ExpiredSignature,              with: :expired_token

    def authenticate_and_restrict_access
      return if current_user

      authenticate_or_request_with_http_token do |authentication_token|
        data = JSONWebToken.decode(authentication_token)
        sign_in User.find(data[:id]), store: false
      end

      authenticate_user! if !current_user and request.format == 'html'
    end

    def invalid_token
      render json: { errors: 'api.invalid_token' }, status: :unauthorized
    end

    def expired_token
      render json: { errors: 'api.expired_token' }, status: :unauthorized
    end
  end
end

你应该能够根据自己的需要来定制

  • 使用
  • 下面是我编写的一个示例,其中包括您可能需要的所有代码和具有工作代码的GitHub repo

  • 这看起来应该适合我的需要。
    是否使用\u http\u令牌对\u或\u请求\u进行身份验证
    是否检查头中是否有令牌或其他内容?我对引擎盖下发生的事情感到有点困惑。您是否将此与Desive一起使用?我是的,但根据我的记忆,我认为这是非常免费的Desive特定代码。在中签名不创建会话吗?您可以检查此宝石: