【发布时间】:2020-08-21 02:32:46
【问题描述】:
我有一个loopback 4 项目,我正在使用@loopback/authentication: ^6.0.0 添加 JWT 身份验证。我关注了official documentaion,并将其连接到我的 MongoDB。所有这一切都很顺利,我可以保护端点。然而,进展已经戛然而止。当用户登录系统时会生成一个 JWT 令牌,我需要在 payload 中添加一个userId。我只是不知道如何向有效负载添加任何内容。
在登录时创建 JWT 的代码是:
@post('/users/login', {
responses: {
'200': {
description: 'Token',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
token: {
type: 'string',
},
},
},
},
},
},
},
})
async login(
@requestBody(CredentialsRequestBody) credentials: Credentials,
): Promise<{token: string}> {
// ensure the user exists, and the password is correct
const user = await this.userService.verifyCredentials(credentials);
// convert a User object into a UserProfile object (reduced set of properties)
const userProfile = this.userService.convertToUserProfile(user);
// create a JSON Web Token based on the user profile
const token = await this.jwtService.generateToken(userProfile);
return {token};
}
我首先尝试将userId 从用户对象手动添加到 userProfile 对象,但没有成功。当我检查generateToken 方法时,我发现它被输入到UserProfile,其定义为:
export interface UserProfile extends Principal {
email?: string;
name?: string;
}
只是为了测试,我尝试添加我的 userID: number; 参数,但这不起作用。生成的有效载荷始终是:
{
"id": "84f0106e-3d47-4af5-8ea3-f8d41194be87",
"name": "chrisloughnane",
"email": "test@gmail.com",
"iat": 1597973078,
"exp": 1597994678
}
name 参数也令人困惑,因为我在 User 对象定义中没有 name。它确实有一个username,它是怎么绑定这个的,我找不到代码。
如何向生成的 JWT 有效负载添加额外参数?
好奇
当向安全端点发出请求时,此 payload 将被处理,因此userId 用于获取正确的数据。我可以编写一个函数来手动解码 payload,是否有内置函数可以做到这一点?
更新:我想出的访问有效负载的解决方案是将SecurityBindings.USER 注入我的控制器的构造函数,然后将其分配给可在任何端点中使用的变量。
constructor(
@repository(IconsRepository)
public iconsRepository: IconsRepository,
@inject(SecurityBindings.USER, {optional: true})
public user: UserProfile,
) {
this.userId = this.user[securityId];
}
【问题讨论】: