由于您正在执行身份验证和/或授权,因此我建议您使用名称绑定过滤器来代替servlet过滤器,以便您可以轻松地将它们绑定到所需的资源。
要将过滤器绑定到您的REST端点,JAX-
RS提供了元注释
@NameBinding,可以如下使用:
@NameBinding@Retention(RUNTIME)@Target({TYPE, METHOD})public @interface Secured { }该
@Secured注释将被用来装饰一个过滤器类,它实现
ContainerRequestFilter,让您处理请求。
在
ContainerRequestContext帮助你提取HTTP请求信息(更多详情,看看该
ContainerRequestContextAPI):
@Secured@Provider@Priority(Priorities.AUTHENTICATION)public class SecurityFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { // Use the ContainerRequestContext to extract information from the HTTP request // Information such as the URI, headers and HTTP entity are available }}ContainerRequestFilter#filter()如果用户未通过身份验证/授权,则该方法是中止请求的好地方。为此,您可以使用
ContainerRequestContext#abortWith()或引发异常。
该
@Provider注释标记的扩展接口,应该由JAX-
RS是可发现的实现过程中提供扫描相运行时。
要将过滤器绑定到端点方法或类,请使用
@Secured上面创建的注释对它们进行 注释。对于带有注释的方法和/或类,将执行过滤器。
@Path("/")public class MyEndpoint { @GET @Path("{id}") @Produces("application/json") public Response myUnsecuredMethod(@PathParam("id") Long id) { // This method is not annotated with @Secured // The security filter won't be executed before invoking this method ... } @DELETE @Secured @Path("{id}") @Produces("application/json") public Response mySecuredMethod(@PathParam("id") Long id) { // This method is annotated with @Secured // The security filter will be executed before invoking this method ... }}在上面的示例中,安全过滤器仅针对进行执行,
mySecuredMethod(Long)因为它带有注释
@Secured。
您可以根据需要为REST端点设置任意数量的过滤器。为了确保过滤器的执行顺序,请使用注释它们
@Priority。
强烈建议使用
Priorities该类中定义的值之一(将使用以下顺序):
AUTHENTICATION
AUTHORIZATION
ENTITY_CODER
HEADER_DECORATOR
USER
如果您的过滤器未使用注释
@Priority,则将
USER优先执行过滤器。
您可以将此方法与Jersey安全机制结合使用。
此外,你可以注入
ResourceInfo你的
ContainerRequestFilter:
@Context private ResourceInfo resourceInfo;
它可以用来获取
Method并
Class与请求的URL匹配:
Class<?> resourceClass = resourceInfo.getResourceClass(); Method resourceMethod = resourceInfo.getResourceMethod();
并从中提取注释:
Annotation[] annotations = resourceClass.getDeclaredAnnotations(); PermitAll annotation = resourceMethod.getAnnotation(PermitAll.class);



