令牌拦截器在Angular 8中不起作用

时间:2019-12-18 07:36:17

标签: angular

我尝试在标头中传递JWT令牌。我正在使用以下代码。我注入了身份验证服务和导入的必需文件。但这不起作用。

我想为每个请求将JWT添加到HTTP标头中吗?我该如何实现?我需要我的后端使用授权令牌对每个请求进行身份验证。

Angular应用程序模块代码:

providers: [
   AuthGuard,
   { 
       provide: HTTP_INTERCEPTORS, 
       useClass: TokenInterceptor, 
       multi: true 
   }
]

角度拦截器代码:

import { Inject, Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { switchMap } from 'rxjs/operators';
import { NbAuthJWTToken, NbAuthService, NB_AUTH_TOKEN_INTERCEPTOR_FILTER ,NbAuthToken} from '@nebular/auth';

/**
 * TokenInterceptor
 * @see https://angular.io/guide/http#intercepting-all-requests-or-responses
 */

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    private tokenService: NbAuthJWTToken;

    constructor(private injector: Injector,
        @Inject(NB_AUTH_TOKEN_INTERCEPTOR_FILTER) protected filter) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        debugger;
        if (!this.filter(req)) {
          return this.authService.isAuthenticatedOrRefresh()
            .pipe(
              switchMap(authenticated => {
                if (authenticated) {
                    debugger;
                    return this.authService.getToken().pipe(
                      switchMap((token: NbAuthToken) => {
                        const JWT = `Bearer ${token.getValue()}`;
                        req = req.clone({
                          setHeaders: {
                            Authorization: JWT,
                          },
                        });
                        return next.handle(req);
                      }),
                    )
                } else {
                    // Request is sent to server without authentication so that the client code
                    // receives the 401/403 error and can act as desired ('session expired', redirect to login, aso)
                  return next.handle(req);
                }
              }),
            )
        } else {
      return next.handle(req);
    }
  }

  protected get authService(): NbAuthService {
    return this.injector.get(NbAuthService);
  }

}

我做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试这样做:

req = req.clone({ headers: req.headers.set('Authorization', JWT) });

还要确保逐步执行代码,然后查看会发生什么。确保您在首次生成令牌时将其存储,并从存储中检索该令牌以进行后续调用(我相信您已经在这样做了,但以防万一您没有这样做)。

答案 1 :(得分:-1)

您需要调试代码以检查为什么未添加令牌。但是您可以简化逻辑:

  intercept(req, next) {
    const tokenizedReq = req.clone({
      setHeaders: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    return next.handle(tokenizedReq);
  } 

这样,您尝试为每个请求添加令牌。如果缺少令牌,则用户将获得401的请求。 当用户进行身份验证时,只需将令牌添加到本地存储中即可。