角度> 4.3& < 5.2.3 - JWT拦截器 - 刷新令牌

时间:2017-07-20 10:50:54

标签: angular angular-http-interceptors

重要角度> 4.3& < 5.2.3

我使用HttpClient并创建此拦截器以添加jwt令牌。每一件工作都很完美,但我的做法很糟糕。我在HttpClient拦截器中使用Http。如果我改变

private http: Http,

private http: HttpClient

我收到此循环错误

Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]") 

任何想法如何才能让它发挥作用?

import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor} from "@angular/common/http";
import {HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {Http} from "@angular/http";
import {SiteService} from "../services/site.service";
import {Router} from "@angular/router";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(
    private http: Http,
    private router: Router,
    private siteService: SiteService
) {}

refreshToken() {
    return this.http.get(this.siteService.apiDomain() + '/api/token?token=' + localStorage.getItem('JWToken'), {})
        .map((response: any) => {
            let data = response.json();
            return {
                token: data.token,
                permissions: data.permissions,
                user: data.user,
            };
        })
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('JWToken'))
    });

    return next.handle(clonedRequest).catch((res) => {

        if (res.status === 401 || res.status === 403) {
            return this.refreshToken().flatMap((data) => {
                if (data.token !== '') {
                    localStorage.setItem('currentUser', JSON.stringify(data.user));
                    localStorage.setItem('currentUserPermissions', JSON.stringify(data.permissions));
                    localStorage.setItem('JWToken', data.token);
                } else {
                    localStorage.removeItem('currentUser');
                    localStorage.removeItem('currentUserPermissions');
                    localStorage.removeItem('JWToken');
                    this.router.navigate(['./auth/login']);
                    return Observable.throw(res);
                }
                const clonedRequestRepeat = req.clone({
                    headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('JWToken'))
                });
                return next.handle(clonedRequestRepeat);
            })
        } else {
            return Observable.throw(res);
        }

    });

}
}

对于那些将此拦截器用于其项目但与当前问题无关的人来说,另一个重要的事情是将标头设置为刷新令牌响应至少几秒钟。

->header('Cache-Control', 'public, max-age=45')
->header('Expires', date('D, d M Y H:i:s ', time() + 45).'GMT');

2 个答案:

答案 0 :(得分:8)

我决定不在构造函数中设置authService,而是进入拦截函数。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth header from the service.
    const auth = this.inj.get(AuthenticationService);
    const authToken = auth.getAuthorizationToken();
    ...
}

侯必须首先将Injector添加到构造函数

constructor(
            ...
            private inj: Injector
) {}

答案 1 :(得分:1)

您也可以尝试一下hack来实现服务,例如:

constructor(private injector: Injector) {
  setTimeout(() => {
      this.loginService = this.injector.get(LoginService);
  })
}

这样就不会出现超出最大调用堆栈错误。