我正在尝试为REST API创建过滤器,我已经开发了以下问题,以使用Jax-Rs和Jersey进行基于静止令牌的身份验证。
问题是我调用过滤器的方法似乎不起作用。
这些是我的课程:
secured.java
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Secured {
}
authenticationfilter.java
@Secured
@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 {
// Validate the token
validateToken(token);
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).build());
}
}
private void validateToken(String token) throws Exception {
// Check if it was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}
}
RESTSEVICE.JAVA
@Path("/test")
public class RestService {
TestDAO testDAO;
@GET
@Secured
@Path("/myservice")
@Produces("application/json")
public List<Test> getEverisTests() {
testDAO=(TestDAO) SpringApplicationContext.getBean("testDAO");
long start = System.currentTimeMillis();
List<Test> ret = testDAO.getTests();
long end = System.currentTimeMillis();
System.out.println("TIEMPO TOTAL: " + (end -start));
return ret;
}
}
RestApplication.java
public class RestApplication extends Application{
private Set<Object> singletons = new HashSet<Object>();
public RestApplication() {
singletons.add(new RestService());
singletons.add(new AuthenticationFilter());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
我缺少什么?预先感谢。
您的AuthenticationFilter
可能未注册。
您的应用程序中某个地方很可能有一个Application
子类。使用它注册过滤器:
@ApplicationPath("api")
public class ApiConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> classes = new HashSet<>();
classes.add(AuthenticationFilter.class);
...
return classes;
}
}
解决方案是在此页面上更新reteasy的JBOSS模块,然后选择我使用的Resteasy版本。
感谢您的答案!
我还不能发表评论,所以这是一个答案:
我不明白@Seced机制的工作原理。您是否尝试删除所有@Secreed注释?然后,滤波器应为所有端点处于活动状态。
如果它仍然不起作用,您可能必须在您的应用程序中手动注册它。
如果之后确实有效,您至少有一个提示在哪里寻找问题...