我正在构建 Rails API 并尝试使用 Devise 实现身份验证。我的目标是使用 JWT 令牌进行身份验证,但我在登录过程和使用令牌生成/响应方面遇到了问题。
我已经重写了 Devise::SessionsController 来处理 JSON 请求并在身份验证成功后使用 JWT 令牌进行响应。但是,我在登录过程中遇到
NoMethodError
和 users_url
,可能是由于 Devise 尝试重定向,这不适用于 API 响应。
NoMethodError at /api/v1/users/sign_in
======================================
undefined method `users_url' for #<Api::V1::SessionsController:0x000000000587f0>
> To access an interactive console with this error, point your browser to: /__better_errors
这是我当前设置 Api::V1::SessionsController 的方式:
class Api::V1::SessionsController < Devise::SessionsController
respond_to :json
skip_before_action :verify_signed_out_user, only: :destroy
def create
self.resource = warden.authenticate!(auth_options)
if resource
token = generate_jwt_token(resource)
render json: { user: resource.as_json, token: token }, status: :created
else
render json: { error: 'Invalid email or password' }, status: :unauthorized
end
end
private
def generate_jwt_token(user)
# :)
end
end
devise.rb
# frozen_string_literal: true
Devise.setup do |config|
config.mailer_sender = '[email protected]'
require 'devise/orm/mongoid'
config.case_insensitive_keys = [:email]
config.strip_whitespace_keys = [:email]
config.skip_session_storage = [:http_auth, :params_auth]
config.stretches = Rails.env.test? ? 1 : 12
config.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 8..128
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
config.reset_password_within = 6.hours
config.sign_out_via = :delete
config.responder.error_status = :unprocessable_entity
config.responder.redirect_status = :see_other
config.navigational_formats = ['*/*', :html, :json]
config.jwt do |jwt|
jwt.secret = Rails.application.credentials.devise_jwt_secret_key
jwt.expiration_time = 1.day.to_i
end
end
问题:
如何正确实现
Api::V1::SessionsController
中的登录过程,以避免 Devise 尝试重定向并确保其适合 API 使用?
使用 Devise for Rails API 身份验证生成和处理 JWT 令牌的最佳实践是什么?
我应该如何构建登录和注销操作的 JSON 响应,以使其更容易被前端使用?
任何有关正确设置 Devise 进行 API 身份验证或指出我可能缺少的内容的建议将不胜感激!
我强烈建议不要构建自己的身份验证系统。
既然您已经在使用 Devise,我建议使用 https://github.com/waiting-for-dev/devise-jwt
devise-jwt 是一个 Devise 扩展,它使用 JWT 令牌进行用户身份验证。它遵循默认安全原则。