I have a custom authentication strategy in my loopback 4 app. For authorization, I need to access the request authorization token in the authorization component. The token contains user details. So I have to find current user from token and check if access is allowed or not depending upon their roles.
So how can I access the authorization token in the loopback authorization function?
Thank you in advance
Here is the code
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
}
}