我正在构建一个需要授权标头的新应用。通常我会使用与此scotch.io article中的方法非常相似的内容。但是我注意到,现在通过新的HttpClientModule在Angular 4生态系统中完全支持HTTP拦截器,我正在尝试找到一些关于如何使用它们的文档。
如果我不正确(从4.3开始)这是注入授权标题的最佳做法,我也愿意接受建议。我的想法是,它是最近添加的一个功能,这意味着可能有充分的理由迁移到" Angular Approved"方法
答案 0 :(得分:9)
这个答案借鉴了CodeWarrior链接的official documentation。
Angular允许您创建HttpInterceptor:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
然后您可以将其集成到您的应用中:
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true,
}],
})
export class AppModule {}
要添加授权标头,您可以使用更改的标头克隆请求:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
请注意,拦截器的作用类似于链,因此您可以设置多个拦截器来执行不同的任务。
答案 1 :(得分:3)
向Interceptor的构造函数注入AuthService给了我这个错误:
未捕获错误:提供程序解析错误:无法实例化循环 依赖! InjectionToken_HTTP_INTERCEPTORS(&#34; [ERROR - &gt;]&#34;):in NgModule AppModule在./AppModule@-1:-1
所以我没有将它注入构造函数,而是使用了Injector
的{{1}}而且工作正常。我将令牌存储在@angular/core
并使用基本身份验证。我需要设置
localStorage
以下是我的实施方式:
<强> token.interceptor.ts 强>
Authorization: 'Bearer token_string'
AuthService中的getToken函数
在这里,您可以实现整个逻辑来获取标头或仅获取标记。在我的情况下,我只是调用它来获取JWT标记字符串。
import {Injectable, Injector} from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private injector: Injector) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(AuthService);
if (auth.getToken()) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${auth.getToken()}`
}
});
}
return next.handle(request);
}
}
<强> app.module.ts 强>
导入/**
* Get jwt token
* @returns {string}
*/
getToken(): string {
return localStorage.getItem('token');
}
TokenInterceptor
在import {TokenInterceptor} from './pathToTheFile/token.interceptor';
数组中的@NgModule
下添加以下内容。
providers:
答案 2 :(得分:0)
我推荐的方法存在的问题是,拦截器必须在编译时就知道,而且显然所有这些都在同一模块中。
我选择实现一个拦截器和一系列处理程序功能,这些功能可以在运行时扩展。服务的拦截方法会处理next()逻辑。
服务(基本代码,无验证或维护):
export type HttpHandlerFunction = (req: HttpRequest<any>) => HttpRequest<any>;
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
private _handlers: Array<HttpHandlerFunction> = [];
addHandler(handler: HttpHandlerFunction): void {
this._handlers.push(handler);
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
this._handlers.forEach((handler: HttpHandlerFunction) => {
req = handler(req);
})
return next.handle(req);
}
}
以及用法,在不同模块中的某些服务中:
constructor(injector: Injector) {
const interceptorsArray: Array<any> = injector.get(HTTP_INTERCEPTORS),
interceptor: HttpInterceptorService = interceptorsArray &&
interceptorsArray.filter((i: any) => i instanceof HttpInterceptorService)[0];
if (interceptor) {
interceptor.addHandler((req: HttpRequest<any>) => {
const accessToken = this.getAccessToken();
if (accessToken) {
// doesn't work with direct headers.set, you must clone
req = req.clone({ headers: req.headers.set('Authorization', accessToken) });
}
return req;
});
}