【问题标题】:Angular6 angular-jwt not adding token to request headersAngular6 angular-jwt 不向请求标头添加令牌
【发布时间】:2018-06-22 10:11:10
【问题描述】:

我正在使用angular-jwt 拦截我的请求并添加 JWT 令牌,但这似乎没有发生。

这是我的角度信息:

Angular CLI: 6.0.8
Node: 9.11.2
OS: linux x64
Angular: 6.0.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.8
@angular-devkit/build-angular     0.6.8
@angular-devkit/build-optimizer   0.6.8
@angular-devkit/core              0.6.8
@angular-devkit/schematics        0.6.8
@angular/cli                      6.0.8
@ngtools/webpack                  6.0.8
@schematics/angular               0.6.8
@schematics/update                0.6.8
rxjs                              6.2.1
typescript                        2.7.2
webpack                           4.8.3

这是我的app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains:['127.0.0.1:8000'],
        blacklistedRoutes: ['127.0.0.1:8000/api/v1/accounts/login/', '127.0.0.1:8000/api/v1/signup/'],
        authScheme: 'JWT ',
        throwNoTokenError: true
      }
    }),
    CommonModule,
}

这是我package.json的一部分:

"@angular/router": "^6.0.3",
"@auth0/angular-jwt": "^2.0.0",

对不起,我忘了说我在app.module.ts中定义了一个tokenGetter函数:

export function tokenGetter() {
  return localStorage.getItem('token');
}

【问题讨论】:

    标签: angular angular6 angular2-jwt


    【解决方案1】:

    好像你还没有定义你的tokenGetter 函数。

    export function tokenGetter() {
      return localStorage.getItem('access_token');
    }
    

    【讨论】:

      【解决方案2】:

      现在您只需使用 Angular 的 HTTP 客户端发出请求

      import { HttpClient } from '@angular/common/http';
      
      export class AppComponent {
        constructor(public http: HttpClient) {}
      
        ping() {
          this.http
            .get('http://example.com/api/things')
            .subscribe(data => console.log(data), err => console.log(err));
        }
      }
      

      来源:https://github.com/auth0/angular2-jwt

      【讨论】:

        【解决方案3】:

        The reason is not found 说明为什么不发送身份验证标头,但是我们可以使用 HttpInterceptor 来执行此操作。

        有一篇关于Angular Authentication: Using the Http Client and Http Interceptors 的好文章。

        我们需要创建一个派生自HttpInterceptor 类的TokenInterceptor(为此我创建了特殊文件夹Interceptors):

        import { Injectable } from '@angular/core';
        import { HttpRequest, HttpHandler, HttpEvent,  
            HttpInterceptor} from '@angular/common/http';
        import { AuthService } from '../services/auth.service';
        import { Observable } from 'rxjs';
        
        @Injectable()
        export class TokenInterceptor implements HttpInterceptor {
        
            constructor(public auth: AuthService) {}
        
            intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 
            {
                request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${this.auth.getToken}`
                }
                });
                return next.handle(request);
            }
        }
        

        然后需要将上面的TokenInterceptor添加到app.module.ts中:

        @NgModule({
          declarations: [
            AppComponent        
          ],
          imports: [
            BrowserModule,   
            HttpClientModule,
            AppRoutingModule,
            CommonModule,
            FormsModule,
            ReactiveFormsModule,    
            RouterModule.forRoot([
              { path: '', component: TheComponent }            
            ]),
            JwtModule.forRoot({
              config: {
                tokenGetter: function tokenGetter() {
                  console.log('tokenGetter called = ' + localStorage.getItem('authToken'));
                  return localStorage.getItem('authToken');
                },
                whitelistedDomains: ['localhost:4200'],
                blacklistedRoutes: []
              }
            })
          ],
          providers: [
            {
                provide: HTTP_INTERCEPTORS,
                useClass: TokenInterceptor,
                multi: true
            }
          ],
          bootstrap: [AppComponent]
        })
        export class AppModule { }
        

        AuthService的代码:

        export class AuthService extends AbstractRestService<any> {
            /* The other code is omitted for the brevity */
            get getToken() {
                return localStorage.getItem('authToken');
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-07-16
          • 2019-09-16
          • 1970-01-01
          • 2016-03-17
          • 2020-11-16
          • 2018-10-13
          • 2019-02-27
          • 2019-04-13
          • 1970-01-01
          相关资源
          最近更新 更多