简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM