I am creating an token based authentication system in angular5. With every request I will send a header containing the token ( X-SDB-AUTH-TOKEN
) and with some response with 401 or 403 status code I sed a response header to identify the type of foribidden status like forbidden because key not match return response header AUTH-STATUS :1
and if user not active status AUTH-STATUS:2
etc.. I want to check in the interceptor and if the status code is 401 or 403
and if AUTH-STATUS:2
redirect to user not active page
otherwise if the status code is 401 or 403
and if AUTH-STATUS:1
redirect to key not match page
. How can I verify response code and header value together. How can we easily read response headers and error code. My code till now is
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from
'@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
if (localStorage.getItem('authToken')) {
req = req.clone({
setHeaders: {
'X-SDB-AUTH-TOKEN': localStorage.getItem('authToken')
}
});
}
return next.handle(req)
.catch((error, caught) => {
if (error.status === 401 || error.status === 403) {
localStorage.removeItem('authToken');
this.router.navigate(['/testLogin']);
}
return Observable.throw(error);
}) as any;
}
}
The catch
operator has two parameters .catch((error, caught) => {})
.
error
is of type HttpErrorResponse , it has a field headers
which allows you to get access to the headers collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.