JWo*_*JWo 3 java rest annotations interceptor quarkus
我有一个使用 Quarkus 的 REST API,我想在其中编写一个拦截器,它为 API 中的每个端点获取不同的参数。基本上我想提供字符串并查看它们是否位于请求附带的 JWT 中。我很难根据需要获取参数(作为字符串)。
这是注释:
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();
}
Run Code Online (Sandbox Code Playgroud)
这是使用它的一个端点:
import javax.ws.rs.GET;
import java.util.List;
public class TenantResource {
@GET
@ScopesAllowed({"MyScope", "AnotherScope"})
public List<Tenant> getTenants() {
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对拦截器的尝试:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
让我困惑的是,当我尝试时,System.out.println(ctx.getContextData());我得到:
{io.quarkus.arc.interceptorBindings=[@mypackage.annotations.ScopesAllowed(value={"MyScope", "AnotherScope"})]}
Run Code Online (Sandbox Code Playgroud)
因此,值就在那里,但我不知道如何处理这种类型的对象。它的类型为 Map<String, Object>,但我不知道如何处理该对象以实际获取大括号中的值。我不想执行 toString() 然后进行一些奇怪的字符串操作来获取它们。
我尝试对此进行研究,但没有找到解决方案,而且我现在不知道该去哪里寻找。
用于InvicationContext#getMethod()获取Method正在调用的方法,然后获取该方法的注释。您可以使用以下命令获取所有注释Method#getAnnotations(),也可以使用以下命令获取单个注释(如果存在)Method.getAnnotation(Class<> annotationCls)
Method getTenants = ctx.getMethod();
ScopesAllowed scopesAnnotation = getTenants.getAnnotation(ScopesAllowed.class);
if (scopesAnnotation != null) {
String[] scopesAllowed = scopesAnnotation.value();
}
Run Code Online (Sandbox Code Playgroud)
就是这样,其实并不难。在某些情况下,反思确实可以起到拯救作用。这是一个值得您随身携带的好工具。
| 归档时间: |
|
| 查看次数: |
2083 次 |
| 最近记录: |