I updated my Angular 6 app so that it uses the auth0/angular2-jwt library. After I updated my services now, I get an 401 Unauthorized
error back from my API although a token is attached correctly to the header.
Any requests sent using Angular's HttpClient will automatically have a token attached as an Authorization header.
This is the documentation for that: Usage Injection
So as far as I understood correctly, I don't need to load my token anytime I want to make an request, and than attach it to the headers because it gets loaded automatically. This is my code:
app.module.ts
import { JwtModule } from '@auth0/angular-jwt';
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: () => {
return localStorage.getItem('id_token');
},
throwNoTokenError: true,
whitelistedDomains: ['localhost:3000'],
}
}),
auth.service.ts
import { HttpClient } from '@angular/common/http';
constructor(
public http: HttpClient
) {}
getProfile() {
return this.http.get<profile>('http://localhost:3000/users/profile');
}
If I use Postman with the token from my localStorage, everything works fine and I get back the correct profile data. If I use my Angular-App it doesn't work.
Try this.
import {HttpClient, HttpHeaders} from '@angular/common/http';
return this.http
.get('http://localhost:3000/users/profile', {
headers: new HttpHeaders().set('Authorization', `Bearer ${this.localStorage.getItem('id_token')}`)
});