Java (Jersey 2 + Grizzly 2) 端点的 JAX-RS 自定义资源注释?
Java (Jersey 2 + Grizzly 2) JAX-RS custom resource annotations for endpoints?
我想用某种 "roles" 属性来注释我的所有 JAX-RS 资源,访问控制过滤器将通过上下文读取该属性。这种 JAX-RS 资源的一个例子是 (psuedo):
@Path("foo")
public class FooResource {
@GET
@Context(roles = "admin,user")
public Response foo() {
return Response.noContent().build();
}
}
因此,AccessControlFilter 可以访问资源特定的 "roles" 值:
public class AccessControlFilter {
@Override
public void filter(ContainerRequestContext context) throws IOException {
String accessToken = accessToken(context);
String roles = context.getContext("roles");
// ... validate access Token against roles ...
}
@Nullable
private static String accessToken(ContainerRequestContext context) {
Map<String, Cookie> cookies = context.getCookies();
Cookie accessTokenCookie = cookies.get("access_token");
if (accessTokenCookie != null) {
return accessTokenCookie.getValue();
}
return null;
}
}
我一直在四处挖掘:
- 我在 Jersey 文档中看到了一些实现 Example 16.1. Using SecurityContext for a Resource Selection,但是我正在寻找更普通的 API 来构建简单的访问控制。
- Specifying Authorized Users by Declaring Security Roles
- Example 16.6. Applying javax.annotation.security to JAX-RS resource methods.
- How to access Jersey resource secured by @RolesAllowed
只需将 ResourceInfo
注入过滤器 class。从那里您可以获得资源 Method
。然后只需使用一些反射来获取注释。
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(...) {
Method method = resourceInfo.getResourceMethod();
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
if (anno != null) {
String roles = anno.value();
}
}
我想用某种 "roles" 属性来注释我的所有 JAX-RS 资源,访问控制过滤器将通过上下文读取该属性。这种 JAX-RS 资源的一个例子是 (psuedo):
@Path("foo")
public class FooResource {
@GET
@Context(roles = "admin,user")
public Response foo() {
return Response.noContent().build();
}
}
因此,AccessControlFilter 可以访问资源特定的 "roles" 值:
public class AccessControlFilter {
@Override
public void filter(ContainerRequestContext context) throws IOException {
String accessToken = accessToken(context);
String roles = context.getContext("roles");
// ... validate access Token against roles ...
}
@Nullable
private static String accessToken(ContainerRequestContext context) {
Map<String, Cookie> cookies = context.getCookies();
Cookie accessTokenCookie = cookies.get("access_token");
if (accessTokenCookie != null) {
return accessTokenCookie.getValue();
}
return null;
}
}
我一直在四处挖掘:
- 我在 Jersey 文档中看到了一些实现 Example 16.1. Using SecurityContext for a Resource Selection,但是我正在寻找更普通的 API 来构建简单的访问控制。
- Specifying Authorized Users by Declaring Security Roles
- Example 16.6. Applying javax.annotation.security to JAX-RS resource methods.
- How to access Jersey resource secured by @RolesAllowed
只需将 ResourceInfo
注入过滤器 class。从那里您可以获得资源 Method
。然后只需使用一些反射来获取注释。
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(...) {
Method method = resourceInfo.getResourceMethod();
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
if (anno != null) {
String roles = anno.value();
}
}