strapi jwt的使用
strapi目前我安装的版本是3.1.6
Nodejs版本12.18.4
测试工具apipost
加入jwt验证文件后无法登陆,老版本3.0.0 beta 尝试一次升级,失败了。后续我还要再尝试一次升级。
1.环境
CENTOS7+宝塔
安装完毕后,直接安装pm2
2.安装strapi(想扩容 要收费的,美元299刀)
yarn create strapi-app my-project --quickstart
或
npx create-strapi-app my-project --quickstart
这样安装完会自动启动,在控制台里可以看有没有问题,如果想启动调试,可以用(控制台关闭会停止服务):
Npm start
(要在项目根目录下执行)
想要持续性管理要用命令:
Pm2 start npm --start
3.安装JWT验证逻辑文件
新建文件夹:
/home/my-test/extensions/users-permissions/config/policies(就最后一个有用,前面都有)
新建逻辑文件
permissions.js
文件内容:
--------------------------------------------------------------------------------------------------------------------------
const _ = require('lodash');
module.exports = async (ctx, next) => {
let role;
if (ctx.state.user) {
// request is already authenticated in a different way
return next();
}
if (ctx.request && ctx.request.header && ctx.request.header.authorization) {
try {
const { id } = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
if (id === undefined) {
throw new Error('Invalid token: Token did not contain required fields');
}
// fetch authenticated user
ctx.state.user = await strapi.plugins['users-permissions'].services.user.fetchAuthenticatedUser(id);
} catch (err) {
return handleErrors(ctx, err, 'unauthorized');
}
if (!ctx.state.user) {
return handleErrors(ctx, 'User Not Found', 'unauthorized');
}
role = ctx.state.user.role;
if (role.type === 'root') {
return await next();
}
const store = await strapi.store({
environment: '',
type: 'plugin',
name: 'users-permissions',
});
if (_.get(await store.get({ key: 'advanced' }), 'email_confirmation') && !ctx.state.user.confirmed) {
return handleErrors(ctx, 'Your account email is not confirmed.', 'unauthorized');
}
if (ctx.state.user.blocked) {
return handleErrors(ctx,'Your account has been blocked by the administrator.','unauthorized');
}
}
// Retrieve `public` role.
if (!role) {
role = await strapi.query('role', 'users-permissions').findOne({ type: 'public' }, []);
}
const route = ctx.request.route;
const permission = await strapi.query('permission', 'users-permissions').findOne({
role: role.id,
type: route.plugin || 'application',
controller: route.controller,
action: route.action,
enabled: true,
},[]);
if (!permission) {
return handleErrors(ctx, undefined, 'forbidden');
}
// Execute the policies.
if (permission.policy) {
return await strapi.plugins['users-permissions'].config.policies[permission.policy](ctx, next);
}
// Execute the action.
await next();
};
const handleErrors = (ctx, err = undefined, type) => {throw strapi.errors[type](err);};
--------------------------------------------------------------------------------------------------------------------------
4.重启服务(不多说了)
5.开始设置权限
登录后台→Users→新建个用户(username和password验证用)
6.设置接口访问权限
登录后台→Settings→身份→Public(扩容要钱)进去找到要控制的表API,比如find,选中后右边选择(限制此操作下的)isauthenticated,保存退出,后台设置就完成了,准备测试
7.测试,获得JWT令牌(一般情况都是前端按照KEY生成的,STRAPI是服务器生成的)
打开APIPOST软件,获取地址:
http://10.3.6.98:1337/auth/local
请求BODY选择APPLICATION/JSON:
{
"identifier": "test",
"password": "test"
}
发送请求,返回:
{
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjAxMDIyNjc0LCJleHAiOjE2MDM2MTQ2NzR9.IAdHvzWOaNFuXmWVM8Ib-eriMUi04l0Kr6pHlx0ZCvQ",
"user": {
"id": 1,
"provider": "local",
"confirmed": false,
"blocked": false,
.........................一些信息
"created_at": "2020-09-25T08:05:49.363Z",
"updated_at": "2020-09-25T08:27:06.504Z"
}
}
8.用返回的JWT再请求接口就可以了
打开APIPOST,输入地址:
选择认证 Bearer auth认证(不需要写“Bearer ”),或自己填写头
Authorization
填写参数(“Bearer ”一定要写,并且有个空格,后面带上TOKEN)
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJ5YXlhIiwiaWF0IjoxNjAwOTMwNTIwLCJpc3MiOiJ5YXlhIiwic3ViIjoieWF5YSIsImV4cCI6MTYwMDk2NjUyMH0.lj5bxUBoCiAmC4hDrj15vtW0qlKXzdDAZiF9U6cCyCc
这个时候发送请求,就会成功了。