gpt4 book ai didi

java - 使用 ContainerRequestFilter 在 Jersey WebService 中自定义 @RolesAllowed 角色

转载 作者:搜寻专家 更新时间:2023-11-01 03:27:32 31 4
gpt4 key购买 nike

我使用 ContainerRequestFilter 接口(interface)创建了一个过滤器,并尝试分配返回用户实体的自定义角色。

 @Override
public ContainerRequest filter(ContainerRequest request) {
User user = authenticate(request);
if (user != null) {
request.setSecurityContext(new Authorizer(user));
} else {
throw new WebApplicationException(400);
}
return request;

}

private User authenticate(ContainerRequest request) {

user = new User("erhan", "customRole");


return user;
}

public class Authorizer implements SecurityContext {

private User user;
private Principal principal;

public Authorizer(final User user) {
this.user = user;
this.principal = new Principal() {

public String getName() {
return user.username;
}
};
}

public Principal getUserPrincipal() {
return this.principal;
}

public boolean isUserInRole(String role) {
return (role.equals(user.role));
}

public boolean isSecure() {
return "https".equals(uriInfo.getRequestUri().getScheme());
}

public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
}

public class User {

public String username;
public String role;

public User(String username, String role) {
this.username = username;
this.role = role;
}
}

那个过滤器一切都很好,但是当它进入网络服务时

 @GET
@RolesAllowed({"customRole"})
@Path("/test")
public String getByType(@Context HttpHeaders headers,@Context SecurityContext sc,
@Context HttpServletRequest request) {



return null;
}

它到达网络服务但是当我改变角色时,仍然到达相同的网络服务。我如何在 Jersey 中提供不同的自定义角色?

最佳答案

使用 Jersey 2,您只需注册 RolesAllowedDynamicFeature 并在 web.xml 中保护您的应用程序。比你不需要自定义 SecurityContext 实现。

参见 Jersey custom SecurityContext on EJB jax-rs resource有关详细信息。

关于java - 使用 ContainerRequestFilter 在 Jersey WebService 中自定义 @RolesAllowed 角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9591227/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com