gpt4 book ai didi

java - 使用通用 URL 模式保护 REST 资源

转载 作者:行者123 更新时间:2023-11-30 07:40:21 25 4
gpt4 key购买 nike

我正在使用 REST WS 开发 JEE 应用程序,我想为 web.xml 中的特定角色保护一些特定的 REST 资源

举例来说:我有四个角色:“Role1”、“Role2”、“Role3”和“RoleEdit”

我希望只有角色“RoleEdit”可以访问这些特定资源:

rest/SomePATH/0/Edit
rest/SomePATH/1/Edit
rest/SomePATH/2/Edit
...
rest/SomePATH/10/Edit

rest/SomeOtherPATH/0/Edit
rest/SomeOtherPATH/1/Edit
rest/SomeOtherPATH/2/Edit
...
rest/SomeOtherPATH/10/Edit

其他角色可以访问:

rest/SomePATH/0/query
...
rest/SomeOtherPATH/0/getInfo
...
rest/SomeOtherPATH/0/query
...
rest/SomeOtherPATH/0/getInfo
...

我将以下 URL 模式添加到 RoleEdit 的 web.xml 中:

<security-constraint>
<display-name>EditRessources</display-name>
<web-resource-collection>
<web-resource-name>Edit</web-resource-name>
<description/>
<url-pattern>/rest/*/*/Edit</url-pattern>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>RoleEdit</role-name>
</auth-constraint>
</security-constraint>

安全容器似乎无法识别 "/rest/*/*/Edit" ,因此所有其他角色可以访问最后一个。

有什么方法可以防止在 web.xml 中写入所有资源(只需使用通用模式)。

提前致谢

最佳答案

我解决了问题,感谢@SteveC

第一个 url-pattern 规范是:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

来源=> Url pattern spec ,因此 rest/*/*/path 无法识别

我建议那些使用 jersy RESTFUL API 的人:

1- 在 jersey servlet 容器内的 web.xml 中添加以下配置:

    <init-param>
<param-name>com.sun.jersey.spi.container.ResourceFilters</param-name>
<param-value>
com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory
</param-value>
</init-param>

2- 在 WS(保护方法或服务)中使用 javax.annotation.security.RolesAllowed :举例来说:

@Path("SomePATH")
public class SampleWS{
...

@POST
@Path("{layer}/Edit")
@Produces("application/json")
@RolesAllowed({"RoleEdit"})
public String edit(@PathParam("layer")String layer){
//some code
}
}

仅此而已。

关于java - 使用通用 URL 模式保护 REST 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34783929/

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