【问题标题】:Using Tomcat Basic Auth with new WebApplicationInitializer将 Tomcat Basic Auth 与新的 WebApplicationInitializer 一起使用
【发布时间】:2013-09-23 09:32:03
【问题描述】:

好的,我之前曾在经典 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 类中看不到等价物。有什么帮助吗?谢谢!

【问题讨论】:

    标签: java spring tomcat servlets


    【解决方案1】:

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

    有一些事情你不能用ServletContainerInitializer 或者更具体的ServletContext 做,其中之一是配置一些安全组件,例如login-config

    相反,您可以使用属性metadata-complete 设置为false 同时拥有ServletContainerInitializerweb.xml。例如,

    <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">
    

    然后在其中添加 &lt;login-config&gt; 元素。

    【讨论】:

    • @Bobby 不客气。请留意更新。在未来的版本中,上述内容可能不再适用。
    猜你喜欢
    • 2017-02-17
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多