A1t*_*t0r 2 java rest web-services resteasy
我正在尝试为我根据这些问题开发的 REST API 创建一个过滤器Best Practice for REST token-based authentication with JAX-RS and Jersey。
问题是我调用过滤器的任何方法似乎都不起作用。
这些是我的课程:
安全.java
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Secured {
}
Run Code Online (Sandbox Code Playgroud)
验证过滤器.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
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?提前致谢。
您的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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4318 次 |
| 最近记录: |