如何使user
对象可用于资源中的进一步处理
@Priority(Priorities.AUTHENTICATION)
public static class ResourceAllowedRequestFilter implements ContainerRequestFilter {
private AuthorizationValidation authorizationValidation;
public ResourceAllowedRequestFilter() {
try {
authorizationValidation = new AuthorizationValidation();
} catch (Exception e) {
}
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (userHeader == null) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST).build());
} else {
User user = authorizationValidation.isAuthorizationValid(userHeader)
}
}
}
@GET
@Path("/{page}/{limit}")
public Response getBooks() {
Access user object created in ContainerRequestFilter
}
答案 0 :(得分:2)
Afaig,只有一种方法,名为注射 - 但多种方式使用注射。
这里有两种方法:
您可以实施/使用javax.ws.rs.core.SecurityContext
。因此,您的用户必须实现java.security.Principal
并使用@Context
将SecurityContext注入您的资源。以下基本示例......
您还可以构建并注册Factory并将每个请求的用户注入您的资源。请访问jersey docs,或搜索@ stackoverflow。你会发现很多例子。
SecurityContext(1)示例:
<强> ContainerRequestFilter 强>
@Override
public synchronized void filter(ContainerRequestContext request)
throws IOException {
final User user = authorizationValidation.isAuthorizationValid(userHeader)
// impl
request.setSecurityContext( new MySecurityContext(user) );
// or simple but not the best
request.setSecurityContext( new SecurityContext() {
@Override
public boolean isUserInRole(String role) {
return true; // check roles if you need ...
}
@Override
public boolean isSecure() {
return false; // check HTTPS
}
@Override
public Principal getUserPrincipal() {
return user; // return your user here - User must implement Principal
}
@Override
public String getAuthenticationScheme() {
return null; // ...
}
}
}
<强>资源强>
@Context
protected SecurityContext securityContext;
@GET
@Path("/{page}/{limit}")
public Response getBooks() {
User user = (User)securityContext.getUserPrincipal();
}
祝你有愉快的一天......