I want to restrict API access with an access-key how most of the APIs provide read access to anonymous users. In my use case my frontend isn't guarded with JWT or any token. I won't to prevent any random person post to my API.
I want to give my frontend read access to come endpoint while write access to other. besides frontend I will have other API connecting to my API with different access key which allows read to some end points and write to other.
I have this interceptor
import {
injectable,
Interceptor,
InvocationContext,
InvocationResult,
Provider,
ValueOrPromise
} from '@loopback/core';
/**
* This class will be bound to the application as an `Interceptor` during
* `boot`
*/
@injectable({tags: {key: AccessKeyRestrictionInterceptor.BINDING_KEY}})
export class AccessKeyRestrictionInterceptor implements Provider<Interceptor> {
static readonly BINDING_KEY = `interceptors.${AccessKeyRestrictionInterceptor.name}`;
/*
constructor() {}
*/
/**
* This method is used by LoopBack context to produce an interceptor function
* for the binding.
*
* @returns An interceptor function
*/
value() {
return this.intercept.bind(this);
}
/**
* The logic to intercept an invocation
* @param invocationCtx - Invocation context
* @param next - A function to invoke next interceptor or the target method
*/
async intercept(
invocationCtx: InvocationContext,
next: () => ValueOrPromise<InvocationResult>,
) {
try {
// Add pre-invocation logic here
console.log('invocationCtx.methodName ', invocationCtx.methodName)
console.log('invocationCtx.args[0] ', invocationCtx.args[0])
console.log('invocationCtx.target ', invocationCtx.target)
console.log('pre-invocation', invocationCtx)
const result = await next();
// Add post-invocation logic here
return result;
} catch (err) {
// Add error handling logic here
throw err;
}
}
}
and using it in my controller
@intercept('interceptors.accessKey')
@post('/only-with-access-key')
I want to add some metadata while calling interceptor something like @intercept('interceptors.accessKey', {metadata: { resource: 'Device', scopes: ['read'] }})
.
I know Loopback 4 provides special interceptor @authorize
but I don't belive I can use it without @authenticate('jwt')
. My use case do not have room for authentication. How can I achieve this?