简体   繁体   中英

How can I check if an API token is still valid

I'm using a token for my API, the problem is that when the token is invalid (time to live < 0) there's no way to know it, so you go on and fill out a form and only when you submit it you get the message "invalid token" which is really annoyin. My idea is to write a script that checks the token's time to live every 10sec for example and then if it's invalid I can disable the forms for example or display a box to force the user to reload the page. Maybe you guys have better ideas , so please don't hesitate to share.

You can do this in a very simple way, I would guess you have an "expiration time" set on your server side for your token. You can just return this time and have a JS function check that value every x seconds or on every required action (open a pop/form/etc).

Probably when you return the token your json can look something like

{
    token:"1234567890",
    expire: "1427484624" //timestamp in seconds, easier to compare
}

Then your JS function can be something as simple as:

function isValidToken(token){
    cTs=Math.floor(Date.now() / 1000);
    return (token>=cTs);
}

and that way you can know very easily.

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