I'm working on an Angular app with a Rails API. I'm using Devise Token Auth and the 6.x branch of angular-token. I can CRUD users with no problem, and I can sign in, but when I try to access a restricted resource (one restricted through the before_action :authenticate_user!
helper), I get an error regardless of whether I'm signed in or not.
Relevant controller:
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
A few things:
- I'm definitely signed in according to
angular-token
--TokenService.UserSignedIn()
returnstrue
at the time of the401 Unauthorized response
. - I've enabled CORS.
- I've exposed the following headers in the rack-cors config:
['access-token', 'expiry', 'token-type', 'uid', 'client']
.
Any help would be greatly appreciated.
Example response from signin:
{
"data": {
"id": 1,
"email": "me@example.com",
"provider": "email",
"uid": "me@example.com",
"allow_password_change": false,
"name": null,
"nickname": null,
"image": null
}
}
Angular code:
this.authService.loginUser({
login: '',
password: ''
})
.subscribe(resp => {
if (resp.status === 200) {
this.router.navigate(['/']);
}
},
err => {
// cut for brevity
});
Edit:
I've figured out the problem is with angular-token
not setting the auth headers due to what I believe to be a bug in the following code:
// 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
});
}
Since I don't have apiPath
defined, req.url.match(this.tokenService.apiPath))
is evaluated to false
and thus, the headers are never added.