即使是正确的凭据,基本身份验证也不起作用

Pra*_*kar 1 web.xml jaas jdbcrealm tomcat7

我正在尝试配置Tomcat 7 JDBC领域配置.我完全遵循了本教程:http: //www.avajava.com/tutorials/lessons/how-do-i-use-a-jdbc-realm-with-tomcat-and-mysql.html

我获得了基本身份验证弹出窗口,但即使我输入了正确的凭据,用户也未经过身份验证.我没有收到任何错误消息.

教程指定的Tomcat 5.5,但我使用Tomcat 7.我刚刚换了connectionPasword,并connectionName和动态Web项目的名称.

这是server.xmlJDBC领域配置

    <Realm  className="org.apache.catalina.realm.JDBCRealm"
            driverName="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/tomcat_realm"
            connectionName="root" 
            connectionPassword="root"
            userTable="tomcat_users" 
            userNameCol="user_name" 
            userCredCol="password"
            userRoleTable="tomcat_users_roles" 
            roleNameCol="role_name" />
Run Code Online (Sandbox Code Playgroud)

这是 web.xml

<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/test</url-pattern>
</servlet-mapping>

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Wildcard means whole app requires authentication</web-resource-name>
        <url-pattern>/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>dude</role-name>
    </auth-constraint>

    <user-data-constraint>
        <!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>

<login-config>
    <auth-method>BASIC</auth-method>
</login-config>
Run Code Online (Sandbox Code Playgroud)

我只能看到,我收到有关安全性的消息:

Security role name dude used in an <auth-constraint> without being defined in a <security-role>
Run Code Online (Sandbox Code Playgroud)

你能帮帮我解决这个问题吗?这个问题与Tomcat 7有关吗?

小智 6

根据Java Servlet规范,您需要将dude角色定义为安全角色.为此,请将<security-role>元素添加到您的web.xml,如下所示:

<servlet>
<!-- ... -->
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Wildcard means whole app requires authentication</web-resource-name>
        <url-pattern>/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>dude</role-name>
    </auth-constraint>
<!-- ... -->
</security-constraint>

<login-config>
     <auth-method>BASIC</auth-method>
</login-config>

<security-role>
    <role-name>dude</role-name>
</security-role>
Run Code Online (Sandbox Code Playgroud)

这将允许GET/ POST请求具有该dude角色的任何用户.

我建议你不要包含这些<http-method>元素,因为它们不像你期望的那样工作.包含此元素GETPOST表示安全约束仅适用于这两种方法; 允许任何其他方法.以下是Servlet规范所说的内容:

子元素web-resource-collection标识应用安全性约束的Web应用程序中的那些资源上的资源和HTTP方法的子集.

请参阅此参考以获取详细信