将 Tomcat Basic Auth 与新的 WebApplicationInitializer 结合使用

2024-01-19

好的,我以前曾在经典的 web.xml 中使用过这种技术,但现在我使用 WebApplicationInitializer 时遇到了让它工作的问题。

我的 WebApplicationInitializer 包含以下代码:

HttpConstraintElement constraint = new HttpConstraintElement(
        TransportGuarantee.NONE,
        new String[]{"sponsorUsers"});
ServletSecurityElement servletSecurity =
        new ServletSecurityElement(constraint);
dispatcher.setServletSecurity(servletSecurity);

我试图对 servlet 中的任何资源请求的任何 http 方法都要求基本身份验证(用户名+密码)。 我得到的只是 403 - 没有提示输入用户名。 我怀疑我需要将 auth-method 设置为 BASIC,就像在 xml 中一样:

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>User Auth</realm-name>
</login-config>

但在 Java 类中看不到等效的内容。有什么帮助吗?谢谢!


A WebApplicationInitializer基本上是Servlet 3.0的Spring扩展ServletContainerInitializer.

有几件事是你不能做的ServletContainerInitializer, or ServletContext更具体地说,其中之一是配置一些安全组件,例如login-config.

相反,您可以同时拥有ServletContainerInitializer and a web.xml使用属性metadata-complete set to false。例如,

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="false" version="3.0">

然后您在其中添加您的<login-config>元素。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Tomcat Basic Auth 与新的 WebApplicationInitializer 结合使用 的相关文章

随机推荐