首页 > 解决方案 > 使用 jwt 设计 - 可恢复的 reset_password_by_token

问题描述

我正在开发一个 Rails API,它将通过 jwt 进行身份验证,并希望用户帐户可以恢复。据推测,在通过电子邮件收到他们的重置令牌后,用户将提供他们的新密码和带有 PUT 的令牌https://example.com/users/password,以由 处理/app/controllers/users/passwords_controller#update。目前我有这个passwords_controller.rb(主要是在默认的设计代码中):

  # PUT /resource/password
  def update
    # {"user": {"password": "secret", "password_confirmation": "secret", "reset_password_token": "token_goes_here"}}
    self.resource = resource_class.reset_password_by_token(resource_params) # problem here (line 33)...
    yield resource if block_given?

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      if Devise.sign_in_after_reset_password
        resource.after_database_authentication
        auth_options = {user: {login: resource.username, password: params['user']['password']}}
        warden.authenticate!(auth_options)
        render json: {success: true, jwt: current_token, response: "Authentication successful" }
      else
        render json: {success: false, response: "Authentication failed" }
      end
    else
      set_minimum_password_length
      respond_with resource
    end
  end

问题是reset_password_by_token请求授权:

 app/controllers/users/passwords_controller.rb:33:in `update'
Completed 401 Unauthorized in 220ms (ActiveRecord: 60.8ms | Allocations: 6810)

这对我来说似乎很奇怪,因为我希望用户能够使用令牌(除非过期)登录一次以更改密码。那时我想返回 jwt (因此 using warden.authenticate),以便前端应用程序可以立即使用它来登录用户。

有人能在这里指出我正确的方向吗?

标签: ruby-on-railsdevisejwtdevise-recoverable

解决方案


从概念上讲,使用 Rails 作为 API 提供者时重置密码功能的流程如下:

  • 用户点击前端的重置密码链接。前端对POST /auth/password进行 API 调用,向用户发送电子邮件。
  • 链接(来自用户邮箱)将用户带到服务器(GET /auth/password/edit),验证令牌,然后服务器将用户重定向到前端,并在查询参数中使用令牌的网址。
  • 使用该令牌,前端使用参数对PUT /auth/passwordpassword进行 API 调用并password_confirmation设置新密码。

推荐阅读