我的Loopback 4应用程序中有一个自定义身份验证策略。对于授权,我需要访问授权组件中的请求授权令牌。令牌包含用户详细信息。因此,我必须从令牌中查找当前用户,并根据他们的角色检查是否允许访问。
那么我该如何在环回授权功能中访问授权令牌?
提前谢谢
这是代码
custom-stratery.ts
async authenticate(request: Request): Promise<any | undefined> {
const token: any = this.extractCredentials(
request
);
console.log('cred' + token)
if (token!= null || token!= undefined) {
// need to access tokenin authorization file
const user = await admin.auth().verifyIdToken(token)
const userProfile = await this.userRepository.find({ where: { email: user.email } })
console.log(userProfile)
return userProfile
}
else {
throw new HttpErrors.Unauthorized(`Authorization header not found.`);
}
extractCredentials(request: Request): any {
if (!request.headers.authorization) {
throw new HttpErrors.Unauthorized(`Authorization header not found.`);
}
// for example : Basic Z2l6bW9AZ21haWwuY29tOnBhc3N3b3Jk
const authHeaderValue = request.headers.authorization;
if (!authHeaderValue.startsWith('Bearer')) {
throw new HttpErrors.Unauthorized(
`Authorization header is not of type 'Bearer'.`,
);
}
//split the string into 2 parts. We are interested in the base64 portion
const parts = authHeaderValue.split(' ');
if (parts.length !== 2)
throw new HttpErrors.Unauthorized(
`Authorization header value has too many parts. It must follow the pattern: 'Basic xxyyzz' where xxyyzz is a base64 string.`,
);
const encryptedCredentails = parts[1];
return encryptedCredentails
}
}
authorization.ts
export async function basicAuthorization(
authorizationCtx: AuthorizationContext,
metadata: AuthorizationMetadata,
): Promise<AuthorizationDecision> {
// No access if authorization details are missing
let currentUser: UserProfile;
// access token here
// find current user from token
// allow access if current user has that role
}
}