Lucas Lucas - 1 year ago 149
AngularJS Question

Check access token before http request

I'm creating an app using Angular 1.5.8 and Laravel 5.2. I'm using a library by Luca Degasperi to create Token Based Auth

Via Angular I make a call and I receive access_token, TTL and refresh_token. I store access_token and refresh_token on localStorage. I can use access_token that I get to make calls to get some data from my API. When token expires I'm getting a message that the token is invalid with 401 code

So my question is how to check if the token is still valid before I send a http request to my API? What is the best way to refresh the token? Ok, I can send a request for the refresh my token to https://my.api/oauth?grant_type=refresh_token&refresh_token=f32j93201h00xpaf1, but how to check it before every http request? Can I repeat the call if the response code is 401? And how?

Please, give me some advice :)

Answer Source

I had exactly the same problem few days ago. Angular Error response interceptor is all you need ;) Also, this article was really helpful

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download