为 REST API 使用令牌的正确方法是什么? [英] What's the right way to use tokens for REST APIs?

查看:56
本文介绍了为 REST API 使用令牌的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用令牌访问 REST API.我可以使用一个端点创建一个在 1 小时内到期的令牌,然后使用该令牌在另一个端点获取一些数据.

I need to access a REST API using a token. I am able to create a token that expires in 1 hour using one endpoint and then use that token to fetch some data at another endpoint.

我需要每天多次调用第二个端点,我可以创建一个令牌,然后每次都获取数据,但这感觉很傻,所以我想知道这样做的正确方法是什么.

I need to call the second endpoint multiple times every day and I could just create a token and then fetch the data each time, but that feels silly so I wonder what would be the right way to do this.

我是否应该存储令牌和过期时间,然后重新使用它,直到我知道它在我获得新令牌之前已经过期,或者我应该如何去做?我以前使用过的唯一令牌是不会过期的,所以我不确定如何做到这一点.

Should I be storing the token and the time of expiration and then reusing it until I know it's expired before I get a new token or how should I go about doing this? The only tokens I've used before are ones that don't expire, so I'm not really sure how to do this.

推荐答案

我会实现下面的伪代码逻辑:

I would implement the Pseudocode logic below:

1/a/Chek if token != Null?如果为真,则转到 3/
1/b/如果为假,token==Null,转到 2/

1/a/ Chek if token != Null? If true go to 3/
1/b/ If false, token==Null, go to 2/

2/getToken() {make a resquest for a new token},成功检索到新令牌后调用3/.

2/ getToken() {make a resquest for a new token}, call 3/ after successfully retrieving a new token.

3/queryAPI(token) {查询 REST API}.如果令牌已过期,您将收到错误 401(当人们未能发回正确的错误代码时,有时会出现 400 或 403,请使用您的 API 对其进行测试),使用 try catch、清除(删除)当前令牌,然后转到 2/.如果代码 200 转到 4/

3/ queryAPI(token) {query the REST API}. If the token is expired you will get error 401 (sometimes 400 or 403 when people fail to send back the right error code, test it with your API), using a try catch, purge (delete) the current token and then go to 2/. If code 200 go to 4/

4/???

5/利润

这样你就不需要自己检查令牌是否过期了,API Endpoint 会告诉你

This way you do not need to check yourself if the token is expired, the API Endpoint will tell you

这篇关于为 REST API 使用令牌的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆