devise_token_auth始终返回401未经授权

时间:2018-07-02 11:10:33

标签: ruby-on-rails angular ruby-on-rails-5 rails-api devise-token-auth

我正在使用Rails API开发Angular应用。我正在使用Devise Token Auth6.x branch of angular-token。我可以毫无问题地对用户进行CRUD,并且可以登录,但是当我尝试访问受限制的资源(通过 with tab as ( SELECT REGEXP_SUBSTR ('X,Y,Z', '[^,]+', 1, LEVEL) code FROM DUAL CONNECT BY REGEXP_SUBSTR ('X,Y,Z','[^,]+',1,LEVEL) IS NOT NULL) select test,test1,test2 from test_n where nvl(code,'X') in (select code from tab) 帮助程序受限制的资源)时,无论是否登录,我都会收到错误消息

相关控制器

before_action :authenticate_user!

几件事:

  • 我肯定是根据class QuestionsController < ApplicationController before_action :authenticate_user! # GET /questions.json def index @questions = Question.all # This code is never reached due to the :authenticate_user! helper, # but when I comment it out, I get the following: puts user_signed_in? # => false puts current_user # => nil render json: @questions end 登录的,在angular-tokenTokenService.UserSignedIn()返回了true
  • 我已启用CORS。
  • 我在rack-cors配置中公开了以下标头:401 Unauthorized response

任何帮助将不胜感激。

登录响应示例

['access-token', 'expiry', 'token-type', 'uid', 'client']

角度代码

{
    "data": {
        "id": 1,
        "email": "me@example.com",
        "provider": "email",
        "uid": "me@example.com",
        "allow_password_change": false,
        "name": null,
        "nickname": null,
        "image": null
    }
}

修改

我发现问题出在this.authService.loginUser({ login: '', password: '' }) .subscribe(resp => { if (resp.status === 200) { this.router.navigate(['/']); } }, err => { // cut for brevity }); 上,因为我认为以下代码中的错误,所以未设置auth标头:

angular-token

由于我没有定义// Add the headers if the request is going to the configured server if (this.tokenService.currentAuthData && req.url.match(this.tokenService.apiPath)) { (<any>Object).assign(baseHeaders, { 'access-token': this.tokenService.currentAuthData.accessToken, 'client': this.tokenService.currentAuthData.client, 'expiry': this.tokenService.currentAuthData.expiry, 'token-type': this.tokenService.currentAuthData.tokenType, 'uid': this.tokenService.currentAuthData.uid }); } ,因此apiPath会被评估为req.url.match(this.tokenService.apiPath)),因此永远不会添加标头。

1 个答案:

答案 0 :(得分:2)

我不知道角度令牌,但是我的基于React / Redux的应用程序也遇到了同样的问题-事实证明,这确实只是标题丢失或设置不正确的问题。

出于某种原因,似乎DeviseTokenAuth::型控制器只能通过设置clientaccess-token才能工作,但是对于受DeviseTokenAuth::Concerns::SetUserByToken保护的所有其他资源,您必须设置all标头完全与devise_token_auth所记录的相同。

  • 检查标题的值和格式。
  • 检查标头是否与上一个请求(在您的情况下为身份验证请求)返回的标头完全相同。
  • 还要检查您的映射

config/initializers/devise_token_auth.rb中:

config.headers_names = {:'access-token' => 'access-token',
                     :'client' => 'client',
                     :'expiry' => 'expiry',
                     :'uid' => 'id',
                     :'token-type' => 'token-type' }

(它定义了预期的http标头的名称(不是model / activerecords属性)。