本文介绍了JAX RS,我的过滤器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在工作:最佳JAX-RS和Jersey进行基于REST令牌的身份验证的实践
但是我的过滤器未触发,我的呼叫直接传递到了端点...
But my filter not triggered, my call pass directly to the endpoint...
我的安全界面:
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Secure {
}
我的过滤器:
@Secure
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the HTTP Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Check if the HTTP Authorization header is present and formatted correctly
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header must be provided");
}
// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring("Bearer".length()).trim();
try {
Token tk = new Token();
tk.validarToken(token);
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).build());
}
}
我的终点:
package api;
import filters.Secure;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
@Path("service")
public class Service {
@GET
@Secure
@Path("/sapo")
@Produces("application/json")
@Consumes("application/json")
public Response mySecuredMethod() {
return Response.ok("sapo").build();
}
}
还有我的web.xml(可以吗?):
And my web.xml(Its ok ??):
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>api</param-value>
</init-param>
<init-param>
<param-name>import javax.ws.rs.container.ContainerRequestFilter</param-name>
<param-value>filters.AuthenticationFilter;api.Service</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
我阅读了很多堆栈相关的问题,但找不到错误.
I read a lot of question related in stack, but can not find the error.
有人知道吗?
谢谢.
推荐答案
最后一个答案,但是解决此问题的方法是将AuthenticationFilter添加到您的类中.
Late for answer, but the solution to this problem is to add AuthenticationFilter to your classes.
public class App extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>();
classes.add(MyApis.class);
classes.add(AuthenticationFilter.class);
return classes;
}
}
这篇关于JAX RS,我的过滤器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!