I wanted to use a interceptor(custom annotation) inside a jax-rs service.
1.First,I wrote an annotation class: BasicAuthentication.java:
@NameBinding
@Target( {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BasicAuthentication {
}
2.Then I added the 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.At last,I add a test service with annotation @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();
}
}
But every time I request /api/test/1 with empty header,I can get the correct response,the interceptor seems not work at all.
I'm using Wildfly 10. Thanks in advance.
Finally I worked out.Change the Interceptor to filter:
public class BasicAuthenticationInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext context){
...
}
}
Then it works as expected.
Form JAX-WS API:
Interface for message body reader interceptors that wrap around calls to MessageBodyReader.readFrom(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, java.io.InputStream).
This could be the reason.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.