尽管令牌已正确加载,但未经授权的错误

问题描述 投票:0回答:1

我更新了我的Angular 6应用程序,以便它使用auth0/angular2-jwt库。在我现在更新我的服务之后,虽然令牌已正确附加到标头,但我从API获得了401 Unauthorized错误。

使用Angular的HttpClient发送的任何请求都将自动将令牌附加为Authorization标头。

这是文档:Usage Injection

因此,据我所知,我不需要在我想要发出请求的任何时候加载我的令牌,而是将其附加到头部,因为它会自动加载。这是我的代码:

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');
  }

如果我使用Postman和我的localStorage中的令牌,一切正常,我会找回正确的配置文件数据。如果我使用我的Angular-App它不起作用。

enter image description here

angular auth0 angular2-jwt
1个回答
0
投票

试试这个。

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')}`)
  });
© www.soinside.com 2019 - 2024. All rights reserved.