简体   繁体   English

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

[英]How can I implement JWT authentication in a Rails app in API mode

I have a Rails app that is in API mode.我有一个处于 API 模式的 Rails 应用程序。

Are there any gems that provide simple JWT authentication?有没有提供简单的 JWT 身份验证的 gem?

Yup, the standard JWT gem is great.是的,标准的 JWT gem 很棒。 Just add it to your gemfile:只需将其添加到您的 gemfile 中:

gem 'jwt'

Then I use it as a concern that I can include like:然后我把它作为一个问题,我可以包括:

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

You should be able to tailor this to your needs.您应该能够根据自己的需要进行调整。

  1. use devise-jwt使用设计-jwt
  2. here is an article I have written including all code you may need and GitHub repo that has a working code这是我写的一篇文章,包括您可能需要的所有代码和具有工作代码的 GitHub 存储库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM