I have a custom authentication strategy in my loopback 4 application. Now for authorization, I need to access the token which contains user details. I have created a very basic authorization provider but the problem is this provider is not getting called. Even the console.logs in the authorization provider are not getting displayed. I have also binded this provider in application.ts.
Here is my code.
Thank you in advance
authorize.ts
import { AuthorizationContext, AuthorizationDecision, AuthorizationMetadata, Authorizer } from '@loopback/authorization';
import { inject, Provider } from '@loopback/core';
import { RestBindings, Request } from '@loopback/rest';
export class MyAuthorizationProvider implements Provider<Authorizer> {
constructor(@inject(RestBindings.Http.REQUEST) private req: Request) { }
/**
* @returns authenticateFn
*/
value(): Authorizer {
return this.authorize.bind(this);
}
async authorize(
authorizationCtx: AuthorizationContext,
metadata: AuthorizationMetadata,
) {
console.log('authorize') // not getting displyed
console.log(this.req.headers.authorization) // not getting displyed
if (true) {
console.log(true) //not getting displyed
}
else {
console.log(false) //not getting displyed
}
return AuthorizationDecision.ALLOW;
}
}
controller
@authenticate('firebase')
@authorize({ allowedRoles: ['retailers'] })
@get('url')
application.ts
let app = new Application();
const authOptions: AuthorizationOptions = {
precedence: AuthorizationDecision.DENY,
defaultDecision: AuthorizationDecision.DENY,
};
const binding = app.component(AuthorizationComponent);
app.configure(binding.key).to(authOptions);
app
.bind('authorizationProviders.my-authorizer-provider')
.toProvider(MyAuthorizationProvider)
.tag(AuthorizationTags.AUTHORIZER);
For anyone facing the same issue, there is an issue in documentation. In application.ts replace your code with the following one. In the docs, it is advising to create a new app and that is the reason it is not working. Please see https://github.com/strongloop/loopback-next/issues/6580