是的,不同的身份验证方法可能会导致不同的访问级别。例如,在JWT身份验证中,访问令牌中包含了用户的角色信息,可以根据用户的角色信息来判断用户的访问级别。
以下是一个使用JWT身份验证的示例代码:
// 导入JWT库
const jwt = require('jsonwebtoken');
// 定义密钥
const secretKey = 'my-secret-key';
// 定义用户角色信息
const roles = {
1: 'admin',
2: 'user',
};
// 定义用户信息
const users = {
1: {
id: 1,
name: 'Admin User',
role: 1,
},
2: {
id: 2,
name: 'Normal User',
role: 2,
}
};
// 定义JWT签名函数
function signJWT(user) {
// 生成JWT访问令牌
const token = jwt.sign({
sub: user.id,
role: roles[user.role],
}, secretKey);
return token;
}
// 定义路由
app.post('/login', (req, res) => {
const { username, password } = req.body;
// 验证用户名和密码是否正确
if (username === 'admin' && password === 'admin') {
// 查询用户信息
const user = users[1];
// 生成JWT访问令牌
const token = signJWT(user);
// 返回JWT访问令牌
res.status(200).json({
token,
});
} else {
// 返回错误信息
res.status(401).json({
error: 'Invalid username or password',
});
}
});
// 定义受保护的路由
app.get('/admin', (req, res) => {
// 从请求头中获取JWT访问令牌
const token = req.headers.authorization.split(' ')[1];