过滤请求 - 角4.3+
问题描述:
我有一个认证拦截器,但是,我希望当用户访问像确认账号密码等,这并不需要用户身份验证的组件这个拦截过滤请求并没有被应用。如何去做任何的例子吗?以下是auth拦截器的逻辑:过滤请求 - 角4.3+
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth token from the service.
let authToken = this.authService.getToken();
let authHeader = 'Bearer ' + authToken;
//For requests that are retried, we always want a fresh copy, else the request will have headers added multiple times.
//So Clone the request before adding the new header.
//NOTE: the cache and pragma are required for IE that will otherwise cache all get 200 requests.
const authReq = request.clone({
setHeaders: {
Authorization: authHeader,
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
}
});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
答
对于这种情况,请求的URL有帮助。
假设您的身份验证网址类似于auth/login or auth/refreshToken
,并且您的资源API类似于api/users, api/users/123, api/addUser
,那么您可以通过if
条件来检查请求的内容。 URL匹配的
例子: -
if (request.url.match(/api\//)) { // api call
console.log('api call detected.');
let authToken = this.authService.getToken();
let authHeader = 'Bearer ' + authToken;
const authReq = request.clone({
setHeaders: {
Authorization: authHeader,
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
}
});
return next.handle(authReq);
}
else{ // auth call - you can put esle if conditions if you have more such pattern
console.log('auth call detected.');
return next.handle(request);
}
现在authentication headers
将只被添加到您的API调用(我说的是资源的API调用),以及其他电话将不会被修改。
注:我一直在后台技术如Java,星展银行等。更长 时间,现在是第一次学习的角度,所以回答像 国防部:P,但这个想法是从我最后的Java项目。希望能帮助到你..!! :)