I'm using Tomcat 10 and eclipse to develop a J2E (or Jakarta EE) web application. I followed this tutorial (http://objis.com/tutoriel-securite-declarative-jee-avec-jaas/#partie2) which seems old (it's a french document, because i'm french, sorry if my english isn't perfect), but I also read the Tomcat 10 documentation.
The dataSource works, I followed instructions on this page (https://tomcat.apache.org/tomcat-10.0-doc/jndi-datasource-examples-howto.html#Oracle_8i,_9i_&_10g) and tested it, but it seems that the realm doesn't work, because I can't login successfully. I always have an authentification error, even if I use the right login and password.
I tried a lot of "solutions" to correct this, but no one works. And I still don't know if I have to put the realm tag inside context.xml, server.xml or both. I tried context.xml and both, but i don't see any difference.
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 "%r" %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, has same content as login.jsp, but with an error message.
User table (password hash obtained with digest.bat) : User table
Role table with foreign key on login referencing login column of user table : Role table
This is my project arborescence, if it can help : arborescence
So please, can someone tell me what I did wrong ?
EDIT : I verified that we find the correct hash if we use the parameters specified in the CredentialHandler tag, it match.
That's the java code i used to verify :
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);
}
}
I obtained the same encodedCredential as in data base ("33D6898C30FBE3E48B9A9EA2D5A0DAD01FD8FD809C9E6A6F3911BB23A481FB0F")
I obtained logs concerning realm :
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)
As Piotr P. Karwasz said it, I misspelled dataSourceName in context.xml and server.xml file. I feel bad that I didn't notice it.
But I still have one question : In which document should I put the realm tag ?