似乎 CASL 有 2 个函数来实现这一点,packRules 和 unpackRules。
根据后端的文档,您可以执行以下操作:
import { packRules } from '@casl/ability/extra';
import jwt from 'jsonwebtoken';
import { defineRulesFor } from '../services/appAbility';
app.post('/session', (req, res) => {
const token = jwt.sign({
id: req.user.id,
rules: packRules(defineRulesFor(req.user))
}, 'jwt secret', { expiresIn: '1d' });
res.send({ token });
});
在前端你做:
import { unpackRules } from '@casl/ability/extra'
import jwt from 'jsonwebtoken';
import ability from '../services/appAbility';
export default class LoginComponent {
login(params) {
return http.post('/session')
.then((response) => {
const token = jwt.decode(response.token);
ability.update(unpackRules(token.rules))
});
}
}
https://stalniy.github.io/casl/v4/en/api/casl-ability-extra