如何使用tomcat 10正确配置身份验证?

dxxyhpgq  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(365)

我正在使用Tomcat10和eclipse开发一个j2e(或JakartaEE)web应用程序。我遵循了这个教程(http://objis.com/tutoriel-securite-declarative-jee-avec-jaas/#partie2)这看起来很旧(这是一个法语文档,因为我是法国人,如果我的英语不完美,很抱歉),但我也阅读了Tomcat10文档。
数据源工作正常,我遵循了本页上的说明(https://tomcat.apache.org/tomcat-10.0-doc/jndi-datasource-examples-howto.html#oracle_8i,并对其进行了测试,但该领域似乎不起作用,因为我无法成功登录。我总是有身份验证错误,即使我使用了正确的登录名和密码。
我尝试了很多“解决方案”来纠正这一点,但没有人奏效。我仍然不知道是否必须将领域标记放在context.xml、server.xml或两者中。我尝试了context.xml和两者,但没有发现任何区别。
my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://Java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    version="3.0">

      <!-- Servlet -->

      <servlet>
        <servlet-name>Accueil</servlet-name>
        <servlet-class>servlet.Accueil</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Accueil</servlet-name>
        <url-pattern></url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Bar</servlet-name>
        <servlet-class>servlet.Bar</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Bar</servlet-name>
        <url-pattern>/bar</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Galerie</servlet-name>
        <servlet-class>servlet.Galerie</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Galerie</servlet-name>
        <url-pattern>/galerie</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Cave</servlet-name>
        <servlet-class>servlet.Cave</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Cave</servlet-name>
        <url-pattern>/cave</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Mentions</servlet-name>
        <servlet-class>servlet.Mentions</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Mentions</servlet-name>
        <url-pattern>/mentions-legales</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Plan</servlet-name>
        <servlet-class>servlet.Plan</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Plan</servlet-name>
        <url-pattern>/plan-acces</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Restaurant</servlet-name>
        <servlet-class>servlet.Restaurant</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Restaurant</servlet-name>
        <url-pattern>/restaurant</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>Catalogue</servlet-name>
        <servlet-class>servlet.catalogue</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>Catalogue</servlet-name>
        <url-pattern>/catalogue</url-pattern>
      </servlet-mapping>

      <servlet>
        <servlet-name>AdminCatalogue</servlet-name>
        <servlet-class>servlet.AdminCatalogue</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>AdminCatalogue</servlet-name>
        <url-pattern>/admin/administration-catalogue</url-pattern>
      </servlet-mapping>

      <security-constraint>
        <display-name>Test authentification Tomcat</display-name>
        <!-- Liste des pages protégées -->
        <web-resource-collection>
            <web-resource-name>Page sécurisée</web-resource-name>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <!-- Rôles des utilisateurs ayant le droit d'y accéder -->
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
        <!-- Connection sécurisée -->
        <!-- <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint> -->
      </security-constraint>

      <!-- Configuration de l'authentification -->
      <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>Espace administration</realm-name>
        <form-login-config>
            <form-login-page>/WEB-INF/login.jsp</form-login-page>
            <form-error-page>/WEB-INF/erreur-authentification.jsp</form-error-page>
        </form-login-config>
      </login-config>

      <!-- Rôles utilisés dans l'application -->
      <security-role>
        <description>Administrateur</description>
        <role-name>admin</role-name>
      </security-role>

      <!-- Ajoute taglibs.jsp au début de chaque jsp -->
      <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <include-prelude>/WEB-INF/taglibs.jsp</include-prelude>
        </jsp-property-group>
      </jsp-config>

      <!-- Déclaration de référence à une source de données JNDI -->
      <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/caradoc</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
      </resource-ref>

</web-app>

context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to enable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="SESSIONS.ser" />
    -->
    <Resource name="jdbc/caradoc" auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="Caradoc22600!" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3307/caradoc"/>

     <Realm className="org.apache.catalina.realm.DataSourceRealm" 
        daraSourceName="jdbc/caradoc" localDataSource="true" userTable="utilisateurs"
        userRoleTable="roles" userNameCol="login" userCredCol="mdp"
        roleNameCol="role">
        <CredentialHandler className="org.apache.catalina.realm.SecretKeyCredentialHandler"
                      algorithm="PBKDF2WithHmacSHA512"
                      iterations="100000"
                      keyLength="256"
                      saltLength="16"
        />
     </Realm>
</Context>

server.xml:

<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="9000" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         HTTP Connector: /docs/config/http.html
         AJP  Connector: /docs/config/ajp.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               URIEncoding = "UTF-8" />

    <!-- <Connector port="8443"
           protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150"
           SSLEnabled="true"
           scheme="https"
           secure="true"
           clientAuth="false"
           sslProtocol="TLS"
           keystoreFile="autosigned-cert.keystore"
           keyAlias="tomcat"
           keystorePass="azertyuiop" /> -->
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector protocol="AJP/1.3"
               address="::1"
               port="8009"
               redirectPort="8443" />
    -->

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Realm className="org.apache.catalina.realm.LockOutRealm">
          <Realm className="org.apache.catalina.realm.DataSourceRealm" 
            daraSourceName="jdbc/caradoc" localDataSource="true" userTable="utilisateurs"
            userRoleTable="roles" userNameCol="login" userCredCol="mdp"
            roleNameCol="role">
            <CredentialHandler className="org.apache.catalina.realm.SecretKeyCredentialHandler"
                          algorithm="PBKDF2WithHmacSHA512"
                          iterations="100000"
                          keyLength="256"
                          saltLength="16"
            />
          </Realm>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Connexion Administrateur</title>
</head>
<body>
    <div align="center">
        <h2>Identification</h2>
    </div>
    <form action="j_security_check" method="post" accept-charset="utf-8">
        <table align="center">
            <tr>
                <td>Login : </td>
                <td><input type="text" name="j_username"/></td>
            </tr>
            <tr>
                <td>Mot de passe : </td>
                <td><input type="password" name="j_password"/></td>
            </tr>
        </table>
        <p align="center"><input type="submit" value="Connexion"/></p>
    </form>
</body>
</html>

erreur-authentifiction.jsp的内容与login.jsp相同,但有一条错误消息。
用户表(使用digest.bat获得的密码哈希):用户表
登录时带有外键的角色表引用用户表的登录列:角色表
这是我的项目树木,如果它可以帮助:树木
那么,有人能告诉我我做错了什么吗?
编辑:我验证了如果我们使用credentialhandler标记中指定的参数,我们是否找到了正确的哈希,它是否匹配。
这是我用来验证的java代码:

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class test{

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        String password = "password";
        byte[] salt = hexStringToByteArray("e0cfcb0169f81fc46c861ecefeb7446b");

        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 100000, 256);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");

        byte[] hash = factory.generateSecret(spec).getEncoded();

        String res = bytesToHex(hash);
        System.out.println(res);
    }
}

我获得了与数据库中相同的编码属性(“33D6898C30FBE3E48B9A2D5A0DAD01FD8FD809C9E6A6F3911BB23A481BF0F”)
我获得了关于领域的日志:

juin 10, 2021 1:07:14 PM org.apache.catalina.realm.DataSourceRealm open
SEVERE: Exception lors de l'anthentification
java.lang.NullPointerException: Cannot invoke "String.length()" because "n" is null
    at java.naming/javax.naming.NameImpl.<init>(NameImpl.java:283)
    at java.naming/javax.naming.CompositeName.<init>(CompositeName.java:237)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:174)
    at org.apache.catalina.realm.DataSourceRealm.open(DataSourceRealm.java:385)
    at org.apache.catalina.realm.DataSourceRealm.authenticate(DataSourceRealm.java:255)
    at org.apache.catalina.authenticator.FormAuthenticator.doAuthenticate(FormAuthenticator.java:244)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:633)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:870)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:832)
sirbozc5

sirbozc51#

作为piotr p。karwasz说过,我在context.xml和server.xml文件中拼错了datasourcename。我感到很遗憾,我没有注意到它。
但我仍然有一个问题:我应该把领域标签放在哪个文档中?

相关问题