Angular 5 HttpInterceptor并在头文件中发送授权令牌

时间:2018-04-18 15:08:16

标签: angular http-headers jwt angular5 angular-http-interceptors

我的流程是登录页面 - >主页。

登录页面没有令牌,登录后,服务器提供令牌,用户被重定向到主页。

主页将令牌发送到服务器,验证令牌,服务器发回数据显示在前端。

问题:

HttpInterceptor在登录请求Cannot read property 'token' of null上触发。我希望拦截器以某种方式忽略登录api请求,并且只在令牌存在时才拦截后续调用。

1 个答案:

答案 0 :(得分:5)

你好,你可以在标题中使用键值来区分登录与其他请求,并创建一个拦截器来检查是否存在删除令牌的密钥

import { HttpClient, HttpHeaders } from '@angular/common/http';
...
login(username, password) {
    let headers = new HttpHeaders();
    headers = headers.append('noToken', 'noToken');
    return this.http.post(loginUrl, data, {headers: headers})
    ...
}

然后创建你的拦截器

export class TokenInterceptor implements HttpInterceptor {
constructor() {}

intercept(httpReq: HttpRequest<any>, next: HttpHandler): 
 Observable<HttpEvent<any>> {
 let headers = httpReq.headers
  .set('Content-Type', 'application/json');

 if (headers.get('noToken') === 'noToken') {
   headers = headers.delete('Authorization').delete('noToken');
 }

 const newReq = httpReq.clone({headers: headers});

 return next.handle(newReq);
 }
}

并将其添加到您的应用模块提供商

import { TokenInterceptor } from ...

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

工作解决方案

<强> auth.interceptor.js

export class AuthInterceptor implements HttpInterceptor {
    constructor(public auth: HouseaccountsService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.headers.get('notoken') !== 'noToken') {
            req = req.clone({
                setHeaders: {
                    Authorization: JSON.parse(localStorage.getItem('currentUser')).token
                }
            });
        }

        return next.handle(req);
    }
}

<强> service.ts

login(user) {
        let loginHeaders = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'noToken': 'noToken'
            })
        }
        return this.http.post<any>(this.url + '/login', JSON.stringify(user), loginHeaders);
    }