Rails: 完成了 401 未授权

6

我遇到了这个错误,但是我不知道为什么。我明确地排除了CSRF检查。即使在生产环境中,#webhook方法也能正常工作。其他类似的问题都是关于Devise的,但是我在这个控制器中没有使用Devise。

stripes_controller.rb
class StripesController < ApplicationController
  Stripe.api_key = ENV['STRIPE_PRIVATE']
  protect_from_forgery :except => [:webhook, :create]
  
  def show
  end

  def create
    # Amount in cents
    @amount = params[:amount]
  
    customer = Stripe::Customer.create(
      :email => params[:stripeEmail],
      :source  => params[:stripeToken]
    )
  
    charge = Stripe::Charge.create(
      :customer    => customer.id,
      :amount      => @amount,
      :description => 'Membership Fee',
      :currency    => 'usd'
    )
  
    render :show
  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to stripe_path
  end
routes.rb
resource :stripe do

日志
Started POST "/stripe/" for 127.0.0.1 at 2018-01-03 11:58:17 -0500
Processing by StripesController#create as HTML
  Parameters: {"amount"=>"100", "stripeToken"=>"tok_1BgFZ2IYOmXNPhc121HxNtw0", "stripeEmail"=>"test@example.com"}
  Rendering stripes/show.haml within layouts/application
  Rendered stripes/show.haml within layouts/application (2.0ms)
  User Load (3.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (2.0ms)  BEGIN
   (1.0ms)  COMMIT
Completed 401 Unauthorized in 3533ms (ActiveRecord: 6.0ms)


Started GET "/" for 127.0.0.1 at 2018-01-03 11:58:21 -0500

Rails默认使用:debug日志级别。 http://guides.rubyonrails.org/v5.0/debugging_rails_applications.html#log-levels 我可以通过设置devise.rb来重现此问题。
config.timeout_in = 1.minute # 8.hours

如果我已登录并活跃,它可以正常工作,但是如果会话超时,那么就会导致401问题。

这是浏览器的请求/响应。它显示成功和302响应,而不是401。虽然服务器控制台日志中显示为401。

POST /stripe/ HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 82
Cache-Control: max-age=0
Origin: http://localhost:3000
Content-Type: application/x-www-form-urlencoded
...

HTTP/1.1 302 Found
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Location: http://localhost:3000/
Content-Type: text/html; charset=utf-8

即使按状态排序,即使使用保留日志功能,在浏览器网络日志中也没有单个401响应。

Rails 5.0.2


1
我们需要查看StripesController#create的 _全部_内容,包括任何before_action/after_action回调以及影响它/受其影响的ApplicationController操作。 - ArtOfCode
1
你可能在应用控制器中有一个 authenticate_user 的 before_action。 - Rahul Sharma
@MarekLipka 这里是 application_controller.rb。然而,没有 before_actions 访问用户。 - Chloe
@ArtOfCode 我添加了整个#create,但它无法访问用户。没有before_actionafter_action回调。 - Chloe
很有趣的是,stripes/show被重定向了,事实上似乎在任何before_action上都没有停止。您能否也显示stripes/show.html.haml - Marek Lipka
显示剩余6条评论
2个回答

12

HTTP状态码401表示未经授权,用于身份认证(https://httpstatuses.com/401)。它与CSRF无关。如果情况是这样的话,将会引发ActionController::InvalidAuthenticityToken异常。

我相信您的ApplicationController中有一个before_action来要求用户进行身份验证(或者在routes.rb中,或者在nginx/Apache的配置文件中)。


这里是application_controller.rb,但它不需要用户认证。我只在某些控制器中进行身份验证。 - Chloe

5

根据Marek的建议,我追踪到了问题所在,它位于user_signed_in?函数。该函数将会停止执行并发出302重定向,同时在服务器日志中打印401!

devise.rb
config.timeout_in = 1.minute # 8.hours
stripes_controller.rb
class StripesController < ApplicationController
  layout false
show.haml
%h2 Thank you!
%p 
  Your payment of 
  %strong= number_to_currency(@amount.to_i * 0.01)
  has been received.
- if user_signed_in?
  Signed in
- else
  Signed out
  

如果用户已登录,则页面将正常加载。 如果用户的会话过期,则Devise将重定向并设置快闪消息

日志
Started GET "/stripe" for 127.0.0.1 at 2018-01-03 14:39:08 -0500
Processing by StripesController#show as HTML
  Rendering stripes/show.haml
  User Load (22.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (1.0ms)  BEGIN
   (2.0ms)  COMMIT
  Rendered stripes/show.haml (179.2ms)
Completed 401 Unauthorized in 399ms (ActiveRecord: 52.0ms)


Started GET "/stripe" for 127.0.0.1 at 2018-01-03 14:39:09 -0500
Processing by StripesController#show as HTML
  Rendering stripes/show.haml
  Rendered stripes/show.haml (2.0ms)
Completed 200 OK in 219ms (Views: 99.8ms | ActiveRecord: 0.0ms)

chrome网络日志

我找不到一种方法来检查用户是否登录而无需重定向。

https://duckduckgo.com/?q=rails+devise+%22user_signed_in%22+stop+redirecting&ia=qa

即使在搜索方法时,user_signed_in? 在 Devise API 文档中也不存在! 我希望有一个可选参数。

http://www.rubydoc.info/github/plataformatec/devise/Devise

所以我设置了layout false,这样它就不会使用包含 user_signed_in?application.haml。我希望有更好的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接