Lucas
Lucas

Reputation: 25

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 :)

Upvotes: 1

Views: 2615

Answers (3)

Mattonit
Mattonit

Reputation: 601

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

Upvotes: 0

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

Can't you use the TTL to determine if the token is still active? When you store your tokens in local storage you can add the date/time the token was stored and each time you go to make a service call you can check the TTL against the time the token was stored.

It will only tell you when it expires, though, and not if the token was invalidated for some other reason.

Upvotes: 0

Valentin Roudge
Valentin Roudge

Reputation: 565

You cannot. You have to check against a login. Therefore it's just a re-login.

I guess that if you get a 401, your refresh token is already done.

Though I guess that you can join that refresh token with all your requests? I might be wrong.

Ensure that your token TTL is always up to date by refreshing its TTL from time to time (like with requests to your API).

Upvotes: 0

Related Questions