Я успешно реализовал jwt auth в своем приложении lb4, используя настраиваемую службу, которая реализует службу пользователя из @loopback/authentication-jwt
. Для аутентификации все работает нормально.
Но когда я иду на авторизацию, AuthorizationMetadata
содержит только два поля - id и name. При выдаче токена я использовал множество полей, одно из которых было role
.
Но теперь все остальные поля, такие как роль или адрес электронной почты, не определены. Таким образом, всякий раз, когда я пытаюсь получить доступ к контроллеру, защищенному с помощью декоратора авторизации, я получаю отказ в доступе 501.
Я не могу понять, почему другие свойства не определены.
заранее спасибо
таможня
export class CustomUserService implements UserService<User, Credentials> {
// other code
convertToUserProfile(user: User): UserProfile {
let address = ''
if (user.address) {
address = user.address
}
const profile = {
[securityId]: user.id!.toString(),
name: user.name,
id: user.id,
email: user.email,
role: user.role,
address: user.address
}
console.log(profile)
return profile
}
}
контроллер входа в систему
import {authenticate, TokenService, UserService} from '@loopback/authentication';
export class UserController {
constructor(@inject(SecurityBindings.USER, {optional: true})
public users: UserProfile,){}
//@get login
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};
}
authorizer.ts
import {AuthorizationContext, AuthorizationDecision, AuthorizationMetadata} from '@loopback/authorization';
export async function basicAuthorization(
authorizationCtx: AuthorizationContext,
metadata: AuthorizationMetadata,
): Promise<AuthorizationDecision> {
// No access if authorization details are missing
let currentUser: UserProfile;
if (authorizationCtx.principals.length > 0) {
const user = _.pick(authorizationCtx.principals[0]
, [
'id',
'name',
'role',
'email',
'address'
]);
console.log(user) // contains only id and name
// other code
}
}