Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authorization header stops going through after the browser sits idle for a while. #763

Closed
hassanasad opened this issue Jan 13, 2023 · 7 comments

Comments

@hassanasad
Copy link

hassanasad commented Jan 13, 2023

I am facing a weird issue where the JWT interceptor stops sending the authorization header after the browser is sitting for a while and then if an API request is sent. I am unable to replicate this at will and thats why i dont have reproduction steps. I just see these being reported in the server logs intermittently.

I am on the latest available version 5.1.2 of JWT library
Angular 14.2.8
It happens from both MacOS and Windows on Chrome, Safari etc

It works fine for awhile and then same API calls start missing authorization header

This is the code snippet we have:

export function JwtTokenGetter(): string {
	if ( localStorage ) {
		return localStorage.getItem('token');
	} else {
		return window.localStorage.getItem('token');
	}
}

@NgModule({
	imports: [
		JwtModule.forRoot({
			config: {
				tokenGetter     : JwtTokenGetter,
				allowedDomains  : allowedDomains,
				disallowedRoutes: [new RegExp(/.*skipInterceptors=true.*/im)],
		},
		}),
		[...]
	],
	providers: [
		JwtInterceptor,	// Providing JwtInterceptor allow to inject JwtInterceptor manually into RefreshTokenInterceptor
		{
			provide    : HTTP_INTERCEPTORS,
			useExisting: JwtInterceptor,
			multi      : true,
		},
		{
			provide : HTTP_INTERCEPTORS,
			useClass: RefreshTokenInterceptor,
			multi   : true,
		},
		[...]
	]
})

Any ideas how to debug this?

@hassanasad
Copy link
Author

Tagging @frederikprijck :)

@frederikprijck
Copy link
Member

Based on what's been shared, it's hard to tell what can cause this.

Did you set the skipWhenExpired setting to true?
Is the token expired at all?

@hassanasad
Copy link
Author

hassanasad commented Jan 14, 2023

Thanks for the quickest reply :)

No i dont have that boolean setting skipWhenExpired in my code. I am assuming it will be using default value for it.

Yes the token expires every five minutes and then based on refresh token a new access token is issued.

I see the refresh token logic working in the browser network tab when the API requests fail with a status 401 TokenException HTTP response and new token is issued. Following requests use that new authorization header.

In one of the articles i was reading these sort of issues can happen if an interceptor or HttpClientModule is loaded multiple times. I dont see that in my code. Its only loaded once in core.module.ts file which is imported once in app.module.ts file.
I only see the JwtInterceptor being in the providers list twice, one for the actual interceptor and once for a requirement in RefreshTokenInterceptor. Could that cause any issue ?

@hassanasad
Copy link
Author

This is my refreshToken interceptor in case it helps:

import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, mergeMap, tap } from 'rxjs/operators';
import { JwtInterceptor, JwtHelperService } from '@auth0/angular-jwt';
import { UserService } from '@app/core/services/user.service';


// Logic inspired from https://gist.github.com/Toilal/8849bd63d53bd2df2dd4df92d3b12f26


@Injectable({
	providedIn: 'root',
})
export class RefreshTokenInterceptor implements HttpInterceptor {


	constructor(
		private userService   : UserService,
		private jwtInterceptor: JwtInterceptor,
		private jwtHelper     : JwtHelperService,
	) { }


	public intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {

		const whiteListedDomain  = this.jwtInterceptor.isAllowedDomain( req );
		const isBlacklistedRoute = this.jwtInterceptor.isDisallowedRoute( req );

		if ( whiteListedDomain && !isBlacklistedRoute && !req.url?.toUpperCase().includes('SKIPINTERCEPTORS=TRUE') ) {
			return next.handle( req )
			.pipe(
				tap( ( res ) => {
					if ( res?.type !== 0 ) {
						// Check for API requests other than OPTION types

						// Check if token is close to expiry - we can try refreshing it before hitting API errors
						const token         = this.userService.getToken();
						const tokenExpiring = this.jwtHelper.isTokenExpired( token, 60 );	// Check if its expiring within 60 seconds

						if ( tokenExpiring === true ) {
							this.userService.refreshToken();
						}
					}
				}),
				catchError( ( err ) => {
					const errorResponse = err as HttpErrorResponse;
					if ( errorResponse?.status === 401 && errorResponse?.error?.responseStatus?.errorCode?.toUpperCase() === 'TOKENEXCEPTION' ) {
						// Token has expired - refresh it
						return this.userService.refreshToken()
						.pipe(mergeMap(() => {
							return this.jwtInterceptor.intercept( req, next );
						}));
					}

					return throwError( () => err );
				})
			);
		}

		return next.handle( req );
	}

}

@frederikprijck
Copy link
Member

It does look like your Interceptor could be causing it, i don't understand why it's calling our SDK's interceptor like that.

Can you isolate everything and reproduce it outside of your app for us to look into?

@hassanasad
Copy link
Author

The solution has been inspired by https://gist.github.com/Toilal/8849bd63d53bd2df2dd4df92d3b12f26 so not a 100% sure why its needed to call the jwtInterceptor.intercept. If i comment that part - it doesn't resend the requests again with updated token.

@frederikprijck
Copy link
Member

I'm going to close this are there currently isnt much for us to action.

Happy to reopen if you can provide an example application for us to look into, but I do not believe this is an SDK issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants