gpt4 book ai didi

java - 如何根据 Dropwizard 中路径中的 id 控制对资源的访问

转载 作者:行者123 更新时间:2023-11-30 06:54:48 25 4
gpt4 key购买 nike

我有一个 Dropwizard 应用程序,其中有一个用户资源,我希望允许非管理员用户仅访问他们自己的数据。我还想允许“管理员”访问任何用户的数据。

@GET
@Path("/users/{userId}")
@RolesAllowed(value="admin")
public Response getUser(@Auth final Client client, @PathParam("userId") final String userId)
throws InterruptedException {
return userDAO.getUser(userId);
}

我已经实现了 Dropwizard 的 Authorizer<Principal>界面,这至少授权具有“admin”角色的用户访问资源。

@Override
public boolean authorize(Principal principal, String allowedRolesForResource) {
Set<Roles> userRoles = ((Client) principal).getRoles();
String userId = ((Client) principal).getUserId();

// Create set of all the allowed roles for the resource
Set<Roles> allowedRoles = Arrays.asList(allowedRolesForResource.split("\\s*,\\s*"))
.stream()
.map(Roles::fromName)
.collect(Collectors.toSet());

if(Collections.disjoint(userRoles, allowedRoles)) {
LOGGER.info("User {} does not have any of the allowed roles [{}] for the resource", userId, allowedRolesForResource);
return false;
}
return true;
}

但是,我不确定如何授权非管理员用户仅使用其自己的 userId 访问资源。我个人的 userId 在 authorize 的范围内方法,但是我没有正在请求的资源路径,即/users/123。

有没有办法将请求上下文纳入我的 Authorizer 类的范围,以便我可以根据请求的资源路径和用户 ID 授予访问权限?

最佳答案

只需为管理员创建一条路径,为每个人创建一条路径

@GET
@Path("/users/{userId}")
@RolesAllowed(value="admin")
public Response getUser(@Auth final Client client, @PathParam("userId") final String userId)
throws InterruptedException {
return userDAO.getUser(userId);
}


@GET
@Path("/user")
public Response getUser(@Auth final Client client)
throws InterruptedException {
return userDAO.getUser(client.getUserId());
}

关于java - 如何根据 Dropwizard 中路径中的 id 控制对资源的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055877/

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