I've an REST API using Quarkus, where I want to write an interceptor, which gets different parameters for every endpoint in the API. Basically I want to provide strings and look if they are in a JWT that comes with the request. I struggle with getting the parameters as I need them, as strings.
Here is the annotation:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import javax.enterprise.util.Nonbinding;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ScopesAllowed {
@Nonbinding
String[] value();
}
Here is one endpoint that uses it:
import javax.ws.rs.GET;
import java.util.List;
public class TenantResource {
@GET
@ScopesAllowed({"MyScope", "AnotherScope"})
public List<Tenant> getTenants() {
}
}
Here is my try of an interceptor:
@Interceptor
@Priority(3000)
@ScopesAllowed({})
public class ScopesAllowedInterceptor {
@Inject
JsonWebToken jwt;
@AroundInvoke
public Object validate(InvocationContext ctx) throws Exception {
// get annotation parameters and check JWT
return ctx.proceed();
//or
throw new UnauthorizedException();
}
}
What confuses me here is when I try System.out.println(ctx.getContextData()); I get:
{io.quarkus.arc.interceptorBindings=[@mypackage.annotations.ScopesAllowed(value={"MyScope", "AnotherScope"})]}
Therefore the values are there, but I don't know how to handle this type of object. It is of type Map<String, Object>, but I don't know how to handle that object to actually get the values in the curly brackets. I don't want to do toString() and then some weird string manipulation to get them.
I tried to research on this, but I found no solution and I don't know where to look now.
Use InvicationContext#getMethod() to get the Method that is being called, then get the annotations of the method. You can get all the annotations with Method#getAnnotations() or get a single annotation (if it exists) with Method.getAnnotation(Class<> annotationCls)
Method getTenants = ctx.getMethod();
ScopesAllowed scopesAnnotation = getTenants.getAnnotation(ScopesAllowed.class);
if (scopesAnnotation != null) {
String[] scopesAllowed = scopesAnnotation.value();
}
That's it, it's really not difficult. Reflection can really come to the rescue on some situations. It's a nice tool to have under your toolbelt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With