失效原因:
strapi自动生成的token,默认过期时间为30天,网上查了很多种方式想直接修改token的过期时间,验证之后没有可以用的。
解决方案如下:
原获取token的方式 | 新获取token的方式 |
---|---|
从管理后台手动拿,在前端写死 | 前端新增一个获取token的接口(这个token的过期时间可以设置) |
具体操作如下:
调用http://localhost:1337/auth/local
的POST方法
post-body如下:
注:identifier和password需要去管理后台手动设置,如何设置参考https://juejin.cn/post/6965676280693456933
{
"identifier": "<your email>",
"password": "<your password>"
}
response:
{
"jwt": "<your jwt token>",
"user": {
# the properties of this user
}
}
获取到的jwt可直接用于调用接口
如何设置jwt的过期时间(具体参考官方文档https://strapi.io/documentation/developer-docs/latest/development/plugins/users-permissions.html#token-usage)
在extensions/users-permissions/config/security.json里配置jwt生成选项
注: 需安装额外的依赖包
npm install jsonwebtoken
expiresIn
: 以秒或描述时间跨度 zeit/ms 的字符串表示。
例如:60、“45m”、“10h”、“2 天”、“7d”、“2y”。数值被解释为秒计数。如果您使用字符串,请确保提供时间单位(分钟、小时、天、年等),否则默认使用毫秒单位(“120”等于“120ms”)。
{
"jwt": {
"expiresIn": "1d" //
}
}
注: "identifier": "", "password": "",这些信息是保存在数据库里的,若测试环境进行验证通过之后,记得把测试环境的数据同步到生产环境。
参考链接:
https://strapi.io/documentation/developer-docs/latest/development/plugins/users-permissions.html#permissions-management
https://juejin.cn/post/6965676280693456933
https://stackoverflow.com/questions/62947112/strapi-jwt-token-lifetime
https://github.com/strapi/strapi/issues/1676#issuecomment-409575253