java - 如何仅对某个 url 路径应用 HttpAuthenticationMechanism?

标签 java

我正在按照 java ee 8 jwt 安全示例的结构在我的应用程序中实现基于角色的授权:https://github.com/javaee-samples/javaee8-samples/tree/master/security/jwt .

  1. 我有一个具有基于 session 的安全性和 JSF 的后端应用程序。身份验证和授权由 WebFilter 管理:

    @WebFilter(urlPatterns = "/faces/*")
    public class AuthorizationFilter implements Filter {
    } 
    
  2. 我有一个具有基于 JWT token 的安全性的 REST api,我想在其中实现 HttpAuthenticationMechanism 来管理身份验证和授权。

出于个人兴趣,我希望这两种不同的安全机制并存,并证明我可以实现这两种方式。但是,每次都会调用 HttpAuthenticationMechanism,浏览我的 JSF 应用程序时也是如此。这会导致触发两种相互冲突的机制。

是否可以将 HttpAuthenticationMechanism 仅应用于特定的 url 路径?就像 WebFilter 中使用的 urlPattern 一样?如果是这样,一个怎么办?

我只想使用 HttpAuthenticationMechanism 在我的其余应用程序中触发:

@ApplicationPath("rest")
public class RestApplication extends Application {

    public RestApplication() {
    }
}

最佳答案

HttpMessageContext 中有一个方法“isProtected”,它会根据 web.xml 中的安全约束设置为 true/false

public AuthenticationStatus validateRequest(HttpServletRequest request,
   HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {
    if (!httpMessageContext.isProtected()) {
        return httpMessageContext.doNothing();
    }
    ...

所以要做的第一件事是检查 isProtected,只有在资源应该受到保护时才继续。

现在您可以像往常一样在 web.xml 中使用安全约束:

...
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Restricted</web-resource-name>
        <description>Declarative security tests</description>
        <url-pattern>/protected/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>somegroup</role-name>
    </auth-constraint>
    <user-data-constraint>
        <description>no description</description>
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>

<security-role>
    <description>Somegroup</description>
    <role-name>somegroup</role-name>
</security-role>
...

现在只会对/protected/* 模式下的 URL 进行身份验证,其他任何内容都可以不 protected

想知道为什么大多数教程/示例中都没有解决这个问题......

感谢此链接,该链接似乎是唯一对此进行描述的链接(尽管 list 16 中缺少一个“NOT”) https://www.informatik-aktuell.de/entwicklung/programmiersprachen/authentication-mit-java-ee-8.html

关于java - 如何仅对某个 url 路径应用 HttpAuthenticationMechanism?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55858623/

相关文章:

java - Eclipse BlackBerry 应用程序中未找到源错误

Java : fill circle partially and put percentage number inside it

java - 使用java将音频文件转换为文本文件

java - 创建和填充表的顺序

java - 将一个测试资源移动到 Maven 中磁盘上的某个位置

java - 反转句子后如何在单词之间打印空格

java - 如何将两个 URL 路由映射到 Spring MVC (3.0) 中的同一个处理程序方法?

java - 在java中调用函数而不声明对象

java - LibGDX - 让 Actor 水平填充父级

java - @Pattern , JSR303 bean 验证 : regex check max 5 words and not blank