【发布时间】:2018-04-30 23:21:04
【问题描述】:
我想在 jax-rs 服务中使用拦截器(自定义注释)。
1.首先,我写了一个注解类: BasicAuthentication.java:
@NameBinding
@Target( {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BasicAuthentication {
}
2.然后我添加了BasicAuthenticationInterceptor implements javax.ws.rs.ext.ReaderInterceptor
BasicAuthenticationInterceptor.java:
@Provider
@Priority(Priorities.AUTHENTICATION)
@BasicAuthentication
public class BasicAuthenticationInterceptor extends Dumpable implements ReaderInterceptor {
@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
//log.info("authentication here")
String authHeader = context.getHeaders().getFirst(AUTHORIZATION);
if (authHeader == null) {
error("\"authorization\" is not found from the request header.");
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return context.proceed();
}
}
3.最后,我添加了一个带有@BasicAuthentication注解的测试服务。
TestRestfulService.java
@Stateless
@Path("/api")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@BasicAuthentication
public class TestRestfulService extends Dumpable{
@EJB
LocalService localService;
@Path("/test/{id}")
@GET
public Response test(@PathParam("id")String id) {
try {
localService.findUser(id);
} catch (Exception e) {
error(e);
return Response.serverError().build();
}
return Response.ok().build();
}
}
但是每次我用空头请求 /api/test/1 时,我都能得到正确的响应,拦截器似乎根本不起作用。
我正在使用 Wildfly 10。 提前致谢。
【问题讨论】:
标签: java jax-rs interceptor