make sure we redirect to signin page if we ever get a 401 response.

This commit is contained in:
Jason Kulatunga 2022-09-12 20:33:39 -04:00
parent 87db3cf751
commit 3811599c19
3 changed files with 27 additions and 14 deletions

View File

@ -22,6 +22,7 @@ import { FormsModule } from '@angular/forms';
import { AuthInterceptorService } from './services/auth-interceptor.service'; import { AuthInterceptorService } from './services/auth-interceptor.service';
import { CanActivateAuthGuard } from './services/can-activate.auth-guard'; import { CanActivateAuthGuard } from './services/can-activate.auth-guard';
import {FastenApiService} from './services/fasten-api.service'; import {FastenApiService} from './services/fasten-api.service';
import {Router} from '@angular/router';
@NgModule({ @NgModule({
declarations: [ declarations: [
AppComponent, AppComponent,
@ -44,11 +45,11 @@ import {FastenApiService} from './services/fasten-api.service';
ChartsModule ChartsModule
], ],
providers: [ providers: [
FastenApiService,
{ {
provide: HTTP_INTERCEPTORS, provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptorService, useClass: AuthInterceptorService,
multi: true multi: true,
deps: [FastenApiService, Router]
}, },
CanActivateAuthGuard CanActivateAuthGuard
], ],

View File

@ -1,23 +1,36 @@
import { Injectable, Injector } from '@angular/core'; import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http'; import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import { FastenApiService } from './fasten-api.service'; import { FastenApiService } from './fasten-api.service';
import {Router} from '@angular/router';
import {Observable, of, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class AuthInterceptorService {
constructor(private injector: Injector) { } // based on https://stackoverflow.com/questions/46017245/how-to-handle-unauthorized-requestsstatus-with-401-or-403-with-new-httpclient
export class AuthInterceptorService implements HttpInterceptor {
intercept(req, next) { constructor(private fastenApiService: FastenApiService, private router: Router) { }
const fastenApiService = this.injector.get(FastenApiService);
const fastenApiRequest = req.clone({
// tslint:disable-next-line:max-line-length
headers: req.headers.set('Authorization', 'Bearer ' + fastenApiService.token)
});
return next.handle(fastenApiRequest); private handleAuthError(err: HttpErrorResponse): Observable<any> {
//handle your auth error or rethrow
if (err.status === 401 || err.status === 403) {
//navigate /delete cookies or whatever
this.fastenApiService.logout()
this.router.navigateByUrl(`/auth/signin`);
// if you've caught / handled the error, you don't want to rethrow it unless you also want downstream consumers to have to handle it as well.
return of(err.message); // or EMPTY may be appropriate here
}
return throwError(err);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + this.fastenApiService.token())});
// catch the error, make specific functions for catching specific errors and you can chain through them with more catch operators
return next.handle(authReq).pipe(catchError(x=> this.handleAuthError(x))); //here use an arrow function, otherwise you may get "Cannot read property 'navigate' of undefined" on angular 4.4.2/net core 2/webpack 2.70
//TODO: check if the response is 401, if so we should always redirect to /login
} }
} }

View File

@ -33,7 +33,6 @@ export class FastenApiService {
logout() { logout() {
localStorage.removeItem(this.AUTH_TOKEN_KEY); localStorage.removeItem(this.AUTH_TOKEN_KEY);
this.router.navigateByUrl('/');
} }
signup(newUser: User): Observable<any> { signup(newUser: User): Observable<any> {