我有一个Rails 5 api,我使用authenticate_with_http_token来授权我的请求。
def authenticate_token
authenticate_with_http_token do |token, options|
User.find_by(auth_token: token)
end
end
我已经设置了Rack :: Cors:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :head]
end
end
这适用于我的所有GET和POST请求。但是当我尝试发出PUT请求时,我得到了一个auth错误。
只有在我使用本地Ionic 2服务器时才会出现错误,当我使用Postman时,错误不会发生。
这就是为什么我猜它与CORS设置有关。
有人可以帮忙吗?
使用Ionic时的日志是:
Started PUT "/api/v1/rides/79?do=setdriver" for ::1 at 2017-02-16 11:06:59 -0200
ActiveRecord::SchemaMigration Load (1.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by API::V1::RidesController#update as */*
Parameters: {"headers"=>{"Authorization"=>["Token token=14b61d7dc9a2a145a3cfb357f75356e2"]}, "do"=>"setdriver", "id"=>"79", "ride"=>{}}
Filter chain halted as :require_login! rendered or redirected
Completed 401 Unauthorized in 1ms (Views: 0.6ms | ActiveRecord: 4.2ms)
使用POSTMAN时的日志是:
Started PUT "/api/v1/rides/79?do=setdriver" for ::1 at 2017-02-16 11:26:18 -0200
Processing by API::V1::RidesController#update as */*
Parameters: {"do"=>"setdriver", "id"=>"79"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = $1 LIMIT $2 [["auth_token", "14b61d7dc9a2a145a3cfb357f75356e2"], ["LIMIT", 1]]
参数看起来不同。但如上所述,我使用相同的标题从Ionic 2发出POST和GET请求。
这是我的require_login
def require_login!
if authenticate_token
return true
end
render json: { errors: [ { detail: "Access denied" } ] }, status: 401
end