我正在开发一个带有 Rails API 的 Angular 应用程序。我正在使用Devise Token Auth和angular-token 的 6.x 分支。我可以毫无问题地 CRUD 用户,并且可以登录,但是当我尝试访问受限制的资源(通过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-token
-时的TokenService.UserSignedIn()
回报登录true
的401 Unauthorized response
。 - 我已经启用了 CORS。
- 我在 rack-cors 配置中公开了以下标头
['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
});
编辑:
我发现问题在于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))
被评估为false
,因此永远不会添加标题。