@bhandaribhumin3i wrote:
Hi, I am trying to figure out how to implement the new angular interceptors and handle
401 unauthorized
errors by refreshing the token and retrying the request. This is the guide I have been following: refer examplehow to resend the requests that previously failed. also, I am using ADAL getAdalTokenSilent for the refresh token.
// to check token valid before 2 minutes of token expire checkTokenRefresh(): Promise<IAuthenticationResult> { return new Promise((resolve, reject) => { const authenticationResult = this .store .selectSnapshot(AuthState.getAuthenticationResult); if (authenticationResult.accessToken) { const getUTCDate = moment() .utc() .format("YYYY-MM-DD"); const getUTCTime = moment() .subtract(2, "minutes") .utc() .format("HH:mm:ss"); const now = moment.utc( getUTCDate + " " + getUTCTime, "YYYY-MM-DD HH:mm:ss" ); const isExpire = now.isAfter(authenticationResult.expiresOn); if (isExpire) { this.login() .then((authResponse: IAuthenticationResult) => { resolve(authResponse); }) .catch(error => { reject(error); }); } else { resolve(authenticationResult); } } else { if (environment.production) { reject("error from refresh token check"); } else { resolve(authenticationResult); } } }); }
login method logic for generating a new token.
login(): Promise<IAuthenticationResult> { return new Promise((resolve, reject) => { console.log('m in login'); this.getAdalTokenSilent() .then((authResponse: IAuthenticationResult) => { console.log('im in getAdalTokenSilent then', JSON.stringify(authResponse)); resolve(authResponse); }) .catch((error: any) => { console.log('im in error', JSON.stringify(error)); this.getAdalTokenAsync() .then(resp => { console.log('im in getAdalTokenAsync success', JSON.stringify(resp)); resolve(resp); }) .catch((error) => { console.log('im in getAdalTokenAsync error ', JSON.stringify(error)); reject(error) }); }); }); }
interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // add authorization header with basic auth credentials if available if (!request.headers.has('Content-Type')) { request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') }); } // **TODO: need to check token expire if expire then generate new token and continue my** request request = this.addAuthenticationToken(request); return next.handle(request); } private addAuthenticationToken(request: HttpRequest<any>): HttpRequest<any> { const isAuth = this .store .selectSnapshot(AuthState.getAuthenticated); if (!isAuth) { return request; } // If you are calling an outside domain then do not add the token. // if (!request.url.match(/www.mydomain.com\//)) { // return request; // } const serverToken = this .store .selectSnapshot(AuthState.getAuthenticationResult); return request.clone({ headers: request.headers.set( this.AUTH_HEADER, serverToken.accessToken, ) }); }
Posts: 1
Participants: 1