【发布时间】:2017-09-14 10:54:29
【问题描述】:
我正在尝试为我根据这些问题Best practice for REST token-based authentication with JAX-RS and Jersey 开发的 REST API 创建一个过滤器。
问题是我调用过滤器的任何方法似乎都不起作用。
这些是我的课程:
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
}
}
RestService.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子类是什么样的?
标签: java web-services rest resteasy