Created
July 19, 2017 18:36
-
-
Save joshharms/00d8159900897dc5bed45757e30405f9 to your computer and use it in GitHub Desktop.
Angular Interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { | |
HttpRequest, | |
} from '@angular/common/http'; | |
import { Http, Response, Headers, RequestOptions } from '@angular/http'; | |
import { Subject, Observable } from 'rxjs/Rx'; | |
import { tokenNotExpired } from 'angular2-jwt'; | |
import { environment } from '../../environments/environment'; | |
@Injectable() | |
export class AuthenticationService { | |
private url = environment.constants.authorization_endpoint + "/oauth2/token"; | |
constructor ( private http: Http ) { } | |
public getToken (): string { | |
return localStorage.getItem( 'access_token' ); | |
} | |
public getRefreshToken (): string { | |
return localStorage.getItem( 'refresh_token' ); | |
} | |
public isAuthenticated (): boolean { | |
// get the token | |
const token = this.getToken(); | |
// return a boolean reflecting | |
// whether or not the token is expired | |
return tokenNotExpired( token ); | |
} | |
public refreshToken () { | |
let client_id = environment.constants.client_id; | |
let audience_id = environment.constants.audience_id; | |
let h = new Headers( | |
{ | |
'Accept': 'application/json', | |
'Content-Type': 'application/x-www-form-urlencoded', | |
} ); | |
let options = new RequestOptions( { headers: h } ); | |
let body = `refresh_token=${ this.getRefreshToken() }&grant_type=refresh_token&client_id=${ client_id }&audience_id=${ audience_id }`; | |
return this.http.post( this.url, body, options ).do( resp => { | |
if ( resp ) { | |
localStorage.setItem( 'access_token', resp.json().access_token ); | |
localStorage.setItem( 'refresh_token', resp.json().refresh_token ); | |
} | |
} ).catch( error => { | |
return Observable.of( false ); | |
} ); | |
} | |
cachedRequests: Array<HttpRequest<any>> = []; | |
public collectFailedRequest ( request ): void { | |
this.cachedRequests.push( request ); | |
} | |
public retryFailedRequests (): void { | |
// retry the requests. this method can | |
// be called after the token is refreshed | |
this.cachedRequests.forEach( request => { | |
request = request.clone( { | |
setHeaders: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
Authorization: `Bearer ${ this.getToken() }` | |
} | |
} ); | |
//??What to do here | |
} ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http'; | |
import { AuthenticationService } from './authentication.service'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/map'; | |
@Injectable() | |
export class TokenInterceptor implements HttpInterceptor { | |
constructor ( public auth: AuthenticationService ) { } | |
intercept ( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { | |
request = request.clone( { | |
setHeaders: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
Authorization: `Bearer ${ this.auth.getToken() }` | |
} | |
} ); | |
return next.handle( request ).do(( event: HttpEvent<any> ) => { | |
if ( event instanceof HttpResponse ) { | |
// do stuff with response if you want | |
} | |
}, ( err: any ) => { | |
if ( err instanceof HttpErrorResponse ) { | |
if ( err.status === 401 ) { | |
this.auth.collectFailedRequest( request ); | |
this.auth.refreshToken().subscribe( resp => { | |
if ( !resp ) { | |
} else { | |
this.auth.retryFailedRequests(); | |
} | |
} ); | |
} | |
} | |
} ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core' | |
import { Resolve } from '@angular/router' | |
import { UserService } from '../shared/user.service' | |
@Injectable() | |
export class UserListResolver implements Resolve<any> { | |
constructor ( private userService: UserService ) { } | |
resolve () { | |
return this.userService.getUsers() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ngOnInit () { | |
this.users = this.route.snapshot.data[ 'users' ].results; | |
this.rows = this.users; | |
this.temp = this.users; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, EventEmitter } from '@angular/core'; | |
import { Subject, Observable } from 'rxjs/Rx'; | |
import { HttpClient } from '@angular/common/http'; | |
import { environment } from '../../../environments/environment'; | |
@Injectable() | |
export class UserService { | |
headers: Headers | |
private url = environment.constants.api_endpoint + "/api/user/"; | |
constructor ( private http: HttpClient ) { } | |
getUsers (): Observable<any> { | |
return this.http.get( this.url ).catch( this.handleError ); | |
} | |
private handleError ( error: Response ) { | |
console.log( error.statusText ); | |
//return Observable.throw( error.statusText ); | |
return Observable.of( false ); | |
} | |
} |
I have a problem, assuming many requests at the same time, all requests are 401 errors, I have multiple RefreshToken, if I only collect requests when 401 error, when and where RefreshToken is called in order to retry collecFailRequests
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, did you ever find a solution for your problem? I am facing the same problem and everything i have tried nothing works