【问题标题】:How do I stop devise from trying to redirect to /users/sign_in for API requests?如何阻止设计尝试重定向到 /users/sign_in 以获取 API 请求?
【发布时间】:2021-04-11 15:39:43
【问题描述】:

在我的 react 前端,我有一个 API 请求正在通过 axios 库发送到我的 ruby​​ on rails 后端:

        Axios({
            url: "/terms",
            headers: {
                'Authorization': token
            }
        }).then((response) => {
            console.log(response.request)
            setActiveSet(response.data)
            setActiveSetIndex(0)
        }).catch((error) => {
            console.log(error)
        })

执行上述请求时,我在后端日志中看到以下响应链(ruby on rails):

Started GET "/terms" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by TermsController#index as HTML
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms | Allocations: 491)


Started GET "/users/sign_in" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by Devise::SessionsController#new as JSON
Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 907)


Started GET "/terms" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by TermsController#index as HTML
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms | Allocations: 491)


Started GET "/users/sign_in" for 192.168.1.119 at 2021-01-05 13:54:02 -0700
Cannot render console from 192.168.1.119! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by Devise::SessionsController#new as JSON
Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 905)

.catch 块永远不会被调用。当我查看响应时,我看到 2 个成功的 200 个响应。 401 响应不会显示在前端。

我正在尝试捕获 401 状态代码,然后通过我的反应前端向用户显示登录表单。后端(设计 gem)试图将我重定向到 /users/sign_in,这不是我想要发生的。我只想要一个 401,以便我的 react 应用程序可以显示自己的登录表单,但由于我不知道的原因,axios 仅显示具有 200 个状态的响应。

【问题讨论】:

    标签: ruby-on-rails devise axios devise-jwt


    【解决方案1】:

    您可以通过更改failure app 来修改身份验证失败时的响应:

    module MyNamespace
      class FailureApp < Devise::FailureApp
        def respond
          request.format.json? ? api_response : super
        end
    
        private
        def api_response
          self.status = 401
          self.content_type = 'application/json'
          # optional - send a message in the response body
          # response.body = { error: i18n_message }.to_json
        end
      end
    end
    
    # add to config/initializers/devise.rb
    config.warden do |manager|
      manager.failure_app = MyNamespace::FailureApp
    end
    

    失败的应用程序只是一个基于ActionController::Metal 的基本 Rack 应用程序,当 Warden 抛出时(当用户身份验证失败时)被调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 2015-11-21
      • 2020-12-10
      • 2020-07-18
      相关资源
      最近更新 更多