You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by ma...@apache.org on 2023/01/24 11:02:27 UTC
[tomcat] 03/07: Code cleanup (format). No functional change.
This is an automated email from the ASF dual-hosted git repository.
markt pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 851d88e1b49be9a369fbe6329c9ff51f9154528c
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 09:56:48 2023 +0000
Code cleanup (format). No functional change.
---
.../catalina/realm/AuthenticatedUserRealm.java | 10 +-
java/org/apache/catalina/realm/CombinedRealm.java | 155 ++--
.../org/apache/catalina/realm/DataSourceRealm.java | 102 ++-
.../realm/DigestCredentialHandlerBase.java | 147 ++--
.../apache/catalina/realm/GenericPrincipal.java | 83 +-
.../apache/catalina/realm/JAASCallbackHandler.java | 110 ++-
.../catalina/realm/JAASMemoryLoginModule.java | 116 ++-
java/org/apache/catalina/realm/JAASRealm.java | 338 ++++-----
java/org/apache/catalina/realm/JNDIRealm.java | 843 +++++++++------------
java/org/apache/catalina/realm/LockOutRealm.java | 158 ++--
java/org/apache/catalina/realm/MemoryRealm.java | 47 +-
java/org/apache/catalina/realm/MemoryRuleSet.java | 31 +-
.../realm/MessageDigestCredentialHandler.java | 34 +-
.../catalina/realm/NestedCredentialHandler.java | 7 +-
java/org/apache/catalina/realm/NullRealm.java | 5 +-
java/org/apache/catalina/realm/RealmBase.java | 494 ++++++------
.../apache/catalina/realm/UserDatabaseRealm.java | 52 +-
.../catalina/realm/X509SubjectDnRetriever.java | 3 +-
.../catalina/realm/X509UsernameRetriever.java | 4 +-
19 files changed, 1189 insertions(+), 1550 deletions(-)
diff --git a/java/org/apache/catalina/realm/AuthenticatedUserRealm.java b/java/org/apache/catalina/realm/AuthenticatedUserRealm.java
index ab6c4b9c9e..44cf8da750 100644
--- a/java/org/apache/catalina/realm/AuthenticatedUserRealm.java
+++ b/java/org/apache/catalina/realm/AuthenticatedUserRealm.java
@@ -21,13 +21,11 @@ import java.security.Principal;
/**
* This Realm is intended for use with Authenticator implementations
* ({@link org.apache.catalina.authenticator.SSLAuthenticator},
- * {@link org.apache.catalina.authenticator.SpnegoAuthenticator}) that
- * authenticate the user as well as obtain the user credentials. An
- * authenticated Principal is always created from the user name presented to
- * without further validation.
+ * {@link org.apache.catalina.authenticator.SpnegoAuthenticator}) that authenticate the user as well as obtain the user
+ * credentials. An authenticated Principal is always created from the user name presented to without further validation.
* <p>
- * <strong>Note:</strong> It is unsafe to use this Realm with Authenticator
- * implementations that do not validate the provided credentials.
+ * <strong>Note:</strong> It is unsafe to use this Realm with Authenticator implementations that do not validate the
+ * provided credentials.
*/
public class AuthenticatedUserRealm extends RealmBase {
diff --git a/java/org/apache/catalina/realm/CombinedRealm.java b/java/org/apache/catalina/realm/CombinedRealm.java
index 8c880e6396..807e5c7f34 100644
--- a/java/org/apache/catalina/realm/CombinedRealm.java
+++ b/java/org/apache/catalina/realm/CombinedRealm.java
@@ -38,10 +38,9 @@ import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSName;
/**
- * Realm implementation that contains one or more realms. Authentication is
- * attempted for each realm in the order they were configured. If any realm
- * authenticates the user then the authentication succeeds. When combining
- * realms usernames should be unique across all combined realms.
+ * Realm implementation that contains one or more realms. Authentication is attempted for each realm in the order they
+ * were configured. If any realm authenticates the user then the authentication succeeds. When combining realms
+ * usernames should be unique across all combined realms.
*/
public class CombinedRealm extends RealmBase {
@@ -53,17 +52,15 @@ public class CombinedRealm extends RealmBase {
protected final List<Realm> realms = new ArrayList<>();
/**
- * Add a realm to the list of realms that will be used to authenticate
- * users.
+ * Add a realm to the list of realms that will be used to authenticate users.
+ *
* @param theRealm realm which should be wrapped by the combined realm
*/
public void addRealm(Realm theRealm) {
realms.add(theRealm);
if (log.isDebugEnabled()) {
- sm.getString("combinedRealm.addRealm",
- theRealm.getClass().getName(),
- Integer.toString(realms.size()));
+ sm.getString("combinedRealm.addRealm", theRealm.getClass().getName(), Integer.toString(realms.size()));
}
}
@@ -75,8 +72,7 @@ public class CombinedRealm extends RealmBase {
ObjectName[] result = new ObjectName[realms.size()];
for (Realm realm : realms) {
if (realm instanceof RealmBase) {
- result[realms.indexOf(realm)] =
- ((RealmBase) realm).getObjectName();
+ result[realms.indexOf(realm)] = ((RealmBase) realm).getObjectName();
}
}
return result;
@@ -90,42 +86,34 @@ public class CombinedRealm extends RealmBase {
}
/**
- * Return the Principal associated with the specified username, which
- * matches the digest calculated using the given parameters using the
- * method described in RFC 2069; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username, which matches the digest calculated using the given
+ * parameters using the method described in RFC 2069; otherwise return <code>null</code>.
*
- * @param username Username of the Principal to look up
+ * @param username Username of the Principal to look up
* @param clientDigest Digest which has been submitted by the client
- * @param nonce Unique (or supposedly unique) token which has been used
- * for this request
- * @param realmName Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest :
- * MD5(Method + ":" + uri)
+ * @param nonce Unique (or supposedly unique) token which has been used for this request
+ * @param realmName Realm name
+ * @param md5a2 Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
*/
@Override
- public Principal authenticate(String username, String clientDigest,
- String nonce, String nc, String cnonce, String qop,
- String realmName, String md5a2) {
+ public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+ String qop, String realmName, String md5a2) {
Principal authenticatedUser = null;
for (Realm realm : realms) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
}
- authenticatedUser = realm.authenticate(username, clientDigest, nonce,
- nc, cnonce, qop, realmName, md5a2);
+ authenticatedUser = realm.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realmName, md5a2);
if (authenticatedUser == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSuccess",
- username, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
}
break;
}
@@ -135,8 +123,7 @@ public class CombinedRealm extends RealmBase {
/**
- * Return the Principal associated with the specified user name otherwise
- * return <code>null</code>.
+ * Return the Principal associated with the specified user name otherwise return <code>null</code>.
*
* @param username User name of the Principal to look up
*/
@@ -146,21 +133,18 @@ public class CombinedRealm extends RealmBase {
for (Realm realm : realms) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
}
authenticatedUser = realm.authenticate(username);
if (authenticatedUser == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSuccess",
- username, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
}
break;
}
@@ -170,12 +154,11 @@ public class CombinedRealm extends RealmBase {
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>.
*
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*/
@Override
public Principal authenticate(String username, String credentials) {
@@ -183,21 +166,18 @@ public class CombinedRealm extends RealmBase {
for (Realm realm : realms) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
}
authenticatedUser = realm.authenticate(username, credentials);
if (authenticatedUser == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSuccess",
- username, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
}
break;
}
@@ -213,11 +193,10 @@ public class CombinedRealm extends RealmBase {
*/
@Override
public void setContainer(Container container) {
- for(Realm realm : realms) {
+ for (Realm realm : realms) {
// Set the realmPath for JMX naming
if (realm instanceof RealmBase) {
- ((RealmBase) realm).setRealmPath(
- getRealmPath() + "/realm" + realms.indexOf(realm));
+ ((RealmBase) realm).setRealmPath(getRealmPath() + "/realm" + realms.indexOf(realm));
}
// Set the container for sub-realms. Mainly so logging works.
@@ -228,12 +207,11 @@ public class CombinedRealm extends RealmBase {
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected void startInternal() throws LifecycleException {
@@ -248,8 +226,7 @@ public class CombinedRealm extends RealmBase {
} catch (LifecycleException e) {
// If realm doesn't start can't authenticate against it
iter.remove();
- log.error(sm.getString("combinedRealm.realmStartFail",
- realm.getClass().getName()), e);
+ log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e);
}
}
}
@@ -264,14 +241,12 @@ public class CombinedRealm extends RealmBase {
/**
- * Gracefully terminate the active use of the public methods of this
- * component and implement the requirements of
+ * Gracefully terminate the active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
+ * @exception LifecycleException if this component detects a fatal error that needs to be reported
*/
- @Override
+ @Override
protected void stopInternal() throws LifecycleException {
// Stop this realm, then the sub-realms (reverse order to start)
super.stopInternal();
@@ -309,37 +284,34 @@ public class CombinedRealm extends RealmBase {
}
/**
- * Return the Principal associated with the specified chain of X509
- * client certificates. If there is none, return <code>null</code>.
+ * Return the Principal associated with the specified chain of X509 client certificates. If there is none, return
+ * <code>null</code>.
*
- * @param certs Array of client certificates, with the first one in
- * the array being the certificate of the client itself.
+ * @param certs Array of client certificates, with the first one in the array being the certificate of the client
+ * itself.
*/
@Override
public Principal authenticate(X509Certificate[] certs) {
Principal authenticatedUser = null;
String username = null;
- if (certs != null && certs.length >0) {
+ if (certs != null && certs.length > 0) {
username = certs[0].getSubjectX500Principal().toString();
}
for (Realm realm : realms) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
}
authenticatedUser = realm.authenticate(certs);
if (authenticatedUser == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail", username,
- realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSuccess",
- username, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
}
break;
}
@@ -364,21 +336,18 @@ public class CombinedRealm extends RealmBase {
for (Realm realm : realms) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart",
- gssName, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authStart", gssName, realm.getClass().getName()));
}
authenticatedUser = realm.authenticate(gssContext, storeCred);
if (authenticatedUser == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail",
- gssName, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authFail", gssName, realm.getClass().getName()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSuccess",
- gssName, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authSuccess", gssName, realm.getClass().getName()));
}
break;
}
@@ -399,21 +368,18 @@ public class CombinedRealm extends RealmBase {
for (Realm realm : realms) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authStart",
- gssName, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authStart", gssName, realm.getClass().getName()));
}
authenticatedUser = realm.authenticate(gssName, gssCredential);
if (authenticatedUser == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authFail",
- gssName, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authFail", gssName, realm.getClass().getName()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("combinedRealm.authSuccess",
- gssName, realm.getClass().getName()));
+ log.debug(sm.getString("combinedRealm.authSuccess", gssName, realm.getClass().getName()));
}
break;
}
@@ -438,9 +404,8 @@ public class CombinedRealm extends RealmBase {
protected String getPassword(String username) {
// This method should never be called
// Stack trace will show where this was called from
- UnsupportedOperationException uoe =
- new UnsupportedOperationException(
- sm.getString("combinedRealm.getPassword"));
+ UnsupportedOperationException uoe = new UnsupportedOperationException(
+ sm.getString("combinedRealm.getPassword"));
log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
throw uoe;
}
@@ -449,9 +414,8 @@ public class CombinedRealm extends RealmBase {
protected Principal getPrincipal(String username) {
// This method should never be called
// Stack trace will show where this was called from
- UnsupportedOperationException uoe =
- new UnsupportedOperationException(
- sm.getString("combinedRealm.getPrincipal"));
+ UnsupportedOperationException uoe = new UnsupportedOperationException(
+ sm.getString("combinedRealm.getPrincipal"));
log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
throw uoe;
}
@@ -479,8 +443,7 @@ public class CombinedRealm extends RealmBase {
private class CombinedRealmCredentialHandler implements CredentialHandler {
@Override
- public boolean matches(String inputCredentials,
- String storedCredentials) {
+ public boolean matches(String inputCredentials, String storedCredentials) {
for (Realm realm : realms) {
if (realm.getCredentialHandler().matches(inputCredentials, storedCredentials)) {
return true;
@@ -501,7 +464,7 @@ public class CombinedRealm extends RealmBase {
}
}
return null;
- }
+ }
}
}
diff --git a/java/org/apache/catalina/realm/DataSourceRealm.java b/java/org/apache/catalina/realm/DataSourceRealm.java
index b1eed69a44..e3713a4ef8 100644
--- a/java/org/apache/catalina/realm/DataSourceRealm.java
+++ b/java/org/apache/catalina/realm/DataSourceRealm.java
@@ -31,9 +31,8 @@ import org.apache.catalina.LifecycleException;
import org.apache.naming.ContextBindings;
/**
- * Implementation of <b>Realm</b> that works with any JDBC JNDI DataSource.
- * See the Realm How-To for more details on how to set up the database and
- * for configuration options.
+ * Implementation of <b>Realm</b> that works with any JDBC JNDI DataSource. See the Realm How-To for more details on how
+ * to set up the database and for configuration options.
*
* @author Glenn L. Nielsen
* @author Craig R. McClanahan
@@ -121,8 +120,8 @@ public class DataSourceRealm extends RealmBase {
*
* @param dataSourceName the name of the JNDI JDBC DataSource
*/
- public void setDataSourceName( String dataSourceName) {
- this.dataSourceName = dataSourceName;
+ public void setDataSourceName(String dataSourceName) {
+ this.dataSourceName = dataSourceName;
}
/**
@@ -133,13 +132,12 @@ public class DataSourceRealm extends RealmBase {
}
/**
- * Set to true to cause the datasource to be looked up in the webapp JNDI
- * Context.
+ * Set to true to cause the datasource to be looked up in the webapp JNDI Context.
*
* @param localDataSource the new flag value
*/
public void setLocalDataSource(boolean localDataSource) {
- this.localDataSource = localDataSource;
+ this.localDataSource = localDataSource;
}
/**
@@ -154,7 +152,7 @@ public class DataSourceRealm extends RealmBase {
*
* @param roleNameCol The column name
*/
- public void setRoleNameCol( String roleNameCol ) {
+ public void setRoleNameCol(String roleNameCol) {
this.roleNameCol = roleNameCol;
}
@@ -170,8 +168,8 @@ public class DataSourceRealm extends RealmBase {
*
* @param userCredCol The column name
*/
- public void setUserCredCol( String userCredCol ) {
- this.userCredCol = userCredCol;
+ public void setUserCredCol(String userCredCol) {
+ this.userCredCol = userCredCol;
}
/**
@@ -186,8 +184,8 @@ public class DataSourceRealm extends RealmBase {
*
* @param userNameCol The column name
*/
- public void setUserNameCol( String userNameCol ) {
- this.userNameCol = userNameCol;
+ public void setUserNameCol(String userNameCol) {
+ this.userNameCol = userNameCol;
}
/**
@@ -202,7 +200,7 @@ public class DataSourceRealm extends RealmBase {
*
* @param userRoleTable The table name
*/
- public void setUserRoleTable( String userRoleTable ) {
+ public void setUserRoleTable(String userRoleTable) {
this.userRoleTable = userRoleTable;
}
@@ -218,25 +216,22 @@ public class DataSourceRealm extends RealmBase {
*
* @param userTable The table name
*/
- public void setUserTable( String userTable ) {
- this.userTable = userTable;
+ public void setUserTable(String userTable) {
+ this.userTable = userTable;
}
// --------------------------------------------------------- Public Methods
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>. If there are any errors with the JDBC connection, executing the query or anything we return
+ * null (don't authenticate). This event is also logged, and the connection will be closed so that a subsequent
+ * request will automatically re-open it.
*
- * If there are any errors with the JDBC connection, executing
- * the query or anything we return null (don't authenticate). This
- * event is also logged, and the connection will be closed so that
- * a subsequent request will automatically re-open it.
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
@@ -257,13 +252,10 @@ public class DataSourceRealm extends RealmBase {
return null;
}
- try
- {
+ try {
// Acquire a Principal object for this user
return authenticate(dbConnection, username, credentials);
- }
- finally
- {
+ } finally {
close(dbConnection);
}
}
@@ -281,24 +273,21 @@ public class DataSourceRealm extends RealmBase {
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>.
*
* @param dbConnection The database connection to be used
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
+ *
* @return the associated principal, or <code>null</code> if there is none.
*/
- protected Principal authenticate(Connection dbConnection,
- String username,
- String credentials) {
+ protected Principal authenticate(Connection dbConnection, String username, String credentials) {
// No user or no credentials
// Can't possibly authenticate, don't bother the database then
if (username == null || credentials == null) {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure",
- username));
+ containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure", username));
}
return null;
}
@@ -306,14 +295,13 @@ public class DataSourceRealm extends RealmBase {
// Look up the user's credentials
String dbCredentials = getPassword(dbConnection, username);
- if(dbCredentials == null) {
+ if (dbCredentials == null) {
// User was not found in the database.
// Waste a bit of time as not to reveal that the user does not exist.
getCredentialHandler().mutate(credentials);
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure",
- username));
+ containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure", username));
}
return null;
}
@@ -323,13 +311,11 @@ public class DataSourceRealm extends RealmBase {
if (validated) {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("dataSourceRealm.authenticateSuccess",
- username));
+ containerLog.trace(sm.getString("dataSourceRealm.authenticateSuccess", username));
}
} else {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure",
- username));
+ containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure", username));
}
return null;
}
@@ -386,7 +372,7 @@ public class DataSourceRealm extends RealmBase {
} else {
context = getServer().getGlobalNamingContext();
}
- DataSource dataSource = (DataSource)context.lookup(dataSourceName);
+ DataSource dataSource = (DataSource) context.lookup(dataSourceName);
Connection connection = dataSource.getConnection();
connectionSuccess = true;
return connection;
@@ -424,7 +410,7 @@ public class DataSourceRealm extends RealmBase {
* Return the password associated with the given principal's user name.
*
* @param dbConnection The database connection to be used
- * @param username Username for which password should be retrieved
+ * @param username Username for which password should be retrieved
*
* @return the password for the specified user
*/
@@ -452,7 +438,9 @@ public class DataSourceRealm extends RealmBase {
/**
* Return the Principal associated with the given user name.
+ *
* @param username the user name
+ *
* @return the principal object
*/
@Override
@@ -462,8 +450,7 @@ public class DataSourceRealm extends RealmBase {
return new GenericPrincipal(username, null);
}
try {
- return new GenericPrincipal(username,
- getRoles(dbConnection, username));
+ return new GenericPrincipal(username, getRoles(dbConnection, username));
} finally {
close(dbConnection);
}
@@ -472,7 +459,9 @@ public class DataSourceRealm extends RealmBase {
/**
* Return the roles associated with the given user name.
+ *
* @param username User name for which roles should be retrieved
+ *
* @return an array list of the role names
*/
protected ArrayList<String> getRoles(String username) {
@@ -497,7 +486,7 @@ public class DataSourceRealm extends RealmBase {
* Return the roles associated with the given user name.
*
* @param dbConnection The database connection to be used
- * @param username User name for which roles should be retrieved
+ * @param username User name for which roles should be retrieved
*
* @return an array list of the role names
*/
@@ -525,7 +514,7 @@ public class DataSourceRealm extends RealmBase {
}
return list;
}
- } catch(SQLException e) {
+ } catch (SQLException e) {
containerLog.error(sm.getString("dataSourceRealm.getRoles.exception", username), e);
}
@@ -541,12 +530,11 @@ public class DataSourceRealm extends RealmBase {
// ------------------------------------------------------ Lifecycle Methods
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected void startInternal() throws LifecycleException {
diff --git a/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java b/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java
index 0291df01fb..2743184df0 100644
--- a/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java
+++ b/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java
@@ -31,8 +31,7 @@ import org.apache.tomcat.util.res.StringManager;
*/
public abstract class DigestCredentialHandlerBase implements CredentialHandler {
- protected static final StringManager sm =
- StringManager.getManager(DigestCredentialHandlerBase.class);
+ protected static final StringManager sm = StringManager.getManager(DigestCredentialHandlerBase.class);
public static final int DEFAULT_SALT_LENGTH = 32;
@@ -44,8 +43,8 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * @return the number of iterations of the associated algorithm that will be
- * used when creating a new stored credential for a given input credential.
+ * @return the number of iterations of the associated algorithm that will be used when creating a new stored
+ * credential for a given input credential.
*/
public int getIterations() {
return iterations;
@@ -53,8 +52,9 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * Set the number of iterations of the associated algorithm that will be
- * used when creating a new stored credential for a given input credential.
+ * Set the number of iterations of the associated algorithm that will be used when creating a new stored credential
+ * for a given input credential.
+ *
* @param iterations the iterations count
*/
public void setIterations(int iterations) {
@@ -63,8 +63,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * @return the salt length that will be used when creating a new stored
- * credential for a given input credential.
+ * @return the salt length that will be used when creating a new stored credential for a given input credential.
*/
public int getSaltLength() {
return saltLength;
@@ -72,8 +71,8 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * Set the salt length that will be used when creating a new stored
- * credential for a given input credential.
+ * Set the salt length that will be used when creating a new stored credential for a given input credential.
+ *
* @param saltLength the salt length
*/
public void setSaltLength(int saltLength) {
@@ -82,8 +81,9 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * When checking input credentials against stored credentials will a warning
- * message be logged if invalid stored credentials are discovered?
+ * When checking input credentials against stored credentials will a warning message be logged if invalid stored
+ * credentials are discovered?
+ *
* @return <code>true</code> if logging will occur
*/
public boolean getLogInvalidStoredCredentials() {
@@ -92,11 +92,10 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * Set whether a warning message will be logged if invalid stored
- * credentials are discovered while checking input credentials against
- * stored credentials?
- * @param logInvalidStoredCredentials <code>true</code> to log, the
- * default value is <code>false</code>
+ * Set whether a warning message will be logged if invalid stored credentials are discovered while checking input
+ * credentials against stored credentials?
+ *
+ * @param logInvalidStoredCredentials <code>true</code> to log, the default value is <code>false</code>
*/
public void setLogInvalidStoredCredentials(boolean logInvalidStoredCredentials) {
this.logInvalidStoredCredentials = logInvalidStoredCredentials;
@@ -138,8 +137,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
// Output the simple/old format for backwards compatibility
return serverCredential;
} else {
- StringBuilder result =
- new StringBuilder((saltLength << 1) + 10 + serverCredential.length() + 2);
+ StringBuilder result = new StringBuilder((saltLength << 1) + 10 + serverCredential.length() + 2);
result.append(HexUtils.toHexString(salt));
result.append('$');
result.append(iterations);
@@ -152,16 +150,15 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * Checks whether the provided credential matches the stored credential when
- * the stored credential is in the form salt$iteration-count$credential
+ * Checks whether the provided credential matches the stored credential when the stored credential is in the form
+ * salt$iteration-count$credential
*
* @param inputCredentials The input credential
* @param storedCredentials The stored credential
*
* @return <code>true</code> if they match, otherwise <code>false</code>
*/
- protected boolean matchesSaltIterationsEncoded(String inputCredentials,
- String storedCredentials) {
+ protected boolean matchesSaltIterationsEncoded(String inputCredentials, String storedCredentials) {
if (storedCredentials == null) {
// Stored credentials are invalid
@@ -180,7 +177,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
return false;
}
- String hexSalt = storedCredentials.substring(0, sep1);
+ String hexSalt = storedCredentials.substring(0, sep1);
int iterations = Integer.parseInt(storedCredentials.substring(sep1 + 1, sep2));
@@ -209,8 +206,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
if (logInvalidStoredCredentials) {
// Logging credentials could be a security concern but they are
// invalid and that is probably a bigger problem
- getLog().warn(sm.getString("credentialHandler.invalidStoredCredential",
- storedCredentials));
+ getLog().warn(sm.getString("credentialHandler.invalidStoredCredential", storedCredentials));
}
}
@@ -224,41 +220,33 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * Generates the equivalent stored credentials for the given input
- * credentials, salt and iterations. If the algorithm requires a key length,
- * the default will be used.
+ * Generates the equivalent stored credentials for the given input credentials, salt and iterations. If the
+ * algorithm requires a key length, the default will be used.
*
- * @param inputCredentials User provided credentials
- * @param salt Salt, if any
- * @param iterations Number of iterations of the algorithm associated
- * with this CredentialHandler applied to the
- * inputCredentials to generate the equivalent
- * stored credentials
+ * @param inputCredentials User provided credentials
+ * @param salt Salt, if any
+ * @param iterations Number of iterations of the algorithm associated with this CredentialHandler applied to
+ * the inputCredentials to generate the equivalent stored credentials
*
- * @return The equivalent stored credentials for the given input
- * credentials or <code>null</code> if the generation fails
+ * @return The equivalent stored credentials for the given input credentials or <code>null</code> if the generation
+ * fails
*/
protected abstract String mutate(String inputCredentials, byte[] salt, int iterations);
/**
- * Generates the equivalent stored credentials for the given input
- * credentials, salt, iterations and key length. The default implementation
- * calls ignores the key length and calls
- * {@link #mutate(String, byte[], int)}. Sub-classes that use the key length
- * should override this method.
+ * Generates the equivalent stored credentials for the given input credentials, salt, iterations and key length. The
+ * default implementation calls ignores the key length and calls {@link #mutate(String, byte[], int)}. Sub-classes
+ * that use the key length should override this method.
*
- * @param inputCredentials User provided credentials
- * @param salt Salt, if any
- * @param iterations Number of iterations of the algorithm associated
- * with this CredentialHandler applied to the
- * inputCredentials to generate the equivalent
- * stored credentials
- * @param keyLength Length of the produced digest in bits for
- * implementations where it's applicable
+ * @param inputCredentials User provided credentials
+ * @param salt Salt, if any
+ * @param iterations Number of iterations of the algorithm associated with this CredentialHandler applied to
+ * the inputCredentials to generate the equivalent stored credentials
+ * @param keyLength Length of the produced digest in bits for implementations where it's applicable
*
- * @return The equivalent stored credentials for the given input
- * credentials or <code>null</code> if the generation fails
+ * @return The equivalent stored credentials for the given input credentials or <code>null</code> if the generation
+ * fails
*/
protected String mutate(String inputCredentials, byte[] salt, int iterations, int keyLength) {
return mutate(inputCredentials, salt, iterations);
@@ -266,25 +254,23 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
/**
- * Set the algorithm used to convert input credentials to stored
- * credentials.
+ * Set the algorithm used to convert input credentials to stored credentials.
+ *
* @param algorithm the algorithm
- * @throws NoSuchAlgorithmException if the specified algorithm
- * is not supported
+ *
+ * @throws NoSuchAlgorithmException if the specified algorithm is not supported
*/
public abstract void setAlgorithm(String algorithm) throws NoSuchAlgorithmException;
/**
- * @return the algorithm used to convert input credentials to stored
- * credentials.
+ * @return the algorithm used to convert input credentials to stored credentials.
*/
public abstract String getAlgorithm();
/**
- * @return the default number of iterations used by the
- * {@link CredentialHandler}.
+ * @return the default number of iterations used by the {@link CredentialHandler}.
*/
protected abstract int getDefaultIterations();
@@ -295,21 +281,18 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
protected abstract Log getLog();
/**
- * Implements String equality which always compares all characters in the
- * string, without stopping early if any characters do not match.
+ * Implements String equality which always compares all characters in the string, without stopping early if any
+ * characters do not match.
* <p>
- * <i>Note:</i>
- * This implementation was adapted from {@link MessageDigest#isEqual}
- * which we assume is as optimizer-defeating as possible.
+ * <i>Note:</i> This implementation was adapted from {@link MessageDigest#isEqual} which we assume is as
+ * optimizer-defeating as possible.
*
- * @param s1 The first string to compare.
- * @param s2 The second string to compare.
- * @param ignoreCase <code>true</code> if the strings should be compared
- * without regard to case. Note that "true" here is only guaranteed
- * to work with plain ASCII characters.
+ * @param s1 The first string to compare.
+ * @param s2 The second string to compare.
+ * @param ignoreCase <code>true</code> if the strings should be compared without regard to case. Note that "true"
+ * here is only guaranteed to work with plain ASCII characters.
*
- * @return <code>true</code> if the strings are equal to each other,
- * <code>false</code> otherwise.
+ * @return <code>true</code> if the strings are equal to each other, <code>false</code> otherwise.
*/
public static boolean equals(final String s1, final String s2, final boolean ignoreCase) {
if (s1 == s2) {
@@ -335,7 +318,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
final int index2 = ((i - len2) >>> 31) * i;
char c1 = s1.charAt(i);
char c2 = s2.charAt(index2);
- if(ignoreCase) {
+ if (ignoreCase) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
}
@@ -345,22 +328,18 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
}
/**
- * Implements byte-array equality which always compares all bytes in the
- * array, without stopping early if any bytes do not match.
+ * Implements byte-array equality which always compares all bytes in the array, without stopping early if any bytes
+ * do not match.
* <p>
- * <i>Note:</i>
- * Implementation note: this method delegates to {@link MessageDigest#isEqual}
- * under the assumption that it provides a constant-time comparison of the
- * bytes in the arrays. Java 7+ has such an implementation, but neither the
- * Javadoc nor any specification requires it. Therefore, Tomcat should
- * continue to use <i>this</i> method internally in case the JDK
- * implementation changes so this method can be re-implemented properly.
+ * <i>Note:</i> Implementation note: this method delegates to {@link MessageDigest#isEqual} under the assumption
+ * that it provides a constant-time comparison of the bytes in the arrays. Java 7+ has such an implementation, but
+ * neither the Javadoc nor any specification requires it. Therefore, Tomcat should continue to use <i>this</i>
+ * method internally in case the JDK implementation changes so this method can be re-implemented properly.
*
* @param b1 The first array to compare.
* @param b2 The second array to compare.
*
- * @return <code>true</code> if the arrays are equal to each other,
- * <code>false</code> otherwise.
+ * @return <code>true</code> if the arrays are equal to each other, <code>false</code> otherwise.
*/
public static boolean equals(final byte[] b1, final byte[] b2) {
return MessageDigest.isEqual(b1, b2);
diff --git a/java/org/apache/catalina/realm/GenericPrincipal.java b/java/org/apache/catalina/realm/GenericPrincipal.java
index 039539330d..6728b76789 100644
--- a/java/org/apache/catalina/realm/GenericPrincipal.java
+++ b/java/org/apache/catalina/realm/GenericPrincipal.java
@@ -30,8 +30,8 @@ import org.apache.catalina.TomcatPrincipal;
import org.ietf.jgss.GSSCredential;
/**
- * Generic implementation of <strong>java.security.Principal</strong> that
- * is available for use by <code>Realm</code> implementations.
+ * Generic implementation of <strong>java.security.Principal</strong> that is available for use by <code>Realm</code>
+ * implementations.
*
* @author Craig R. McClanahan
*/
@@ -43,8 +43,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
// ----------------------------------------------------------- Constructors
/**
- * Construct a new Principal, associated with the specified Realm, for the
- * specified username, with no roles.
+ * Construct a new Principal, associated with the specified Realm, for the specified username, with no roles.
*
* @param name The username of the user represented by this Principal
*/
@@ -53,10 +52,10 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
}
/**
- * Construct a new Principal, associated with the specified Realm, for the
- * specified username, with the specified role names (as Strings).
+ * Construct a new Principal, associated with the specified Realm, for the specified username, with the specified
+ * role names (as Strings).
*
- * @param name The username of the user represented by this Principal
+ * @param name The username of the user represented by this Principal
* @param roles List of roles (must be Strings) possessed by this user
*/
public GenericPrincipal(String name, List<String> roles) {
@@ -64,51 +63,45 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
}
/**
- * Construct a new Principal, associated with the specified Realm, for the
- * specified username, with the specified role names (as Strings).
+ * Construct a new Principal, associated with the specified Realm, for the specified username, with the specified
+ * role names (as Strings).
*
- * @param name The username of the user represented by this Principal
- * @param roles List of roles (must be Strings) possessed by this user
- * @param userPrincipal - the principal to be returned from the request
- * getUserPrincipal call if not null; if null, this will be returned
+ * @param name The username of the user represented by this Principal
+ * @param roles List of roles (must be Strings) possessed by this user
+ * @param userPrincipal - the principal to be returned from the request getUserPrincipal call if not null; if null,
+ * this will be returned
*/
- public GenericPrincipal(String name, List<String> roles,
- Principal userPrincipal) {
+ public GenericPrincipal(String name, List<String> roles, Principal userPrincipal) {
this(name, roles, userPrincipal, null);
}
/**
- * Construct a new Principal, associated with the specified Realm, for the
- * specified username, with the specified role names (as Strings).
+ * Construct a new Principal, associated with the specified Realm, for the specified username, with the specified
+ * role names (as Strings).
*
- * @param name The username of the user represented by this Principal
- * @param roles List of roles (must be Strings) possessed by this user
- * @param userPrincipal - the principal to be returned from the request
- * getUserPrincipal call if not null; if null, this will be returned
- * @param loginContext - If provided, this will be used to log out the user
- * at the appropriate time
+ * @param name The username of the user represented by this Principal
+ * @param roles List of roles (must be Strings) possessed by this user
+ * @param userPrincipal - the principal to be returned from the request getUserPrincipal call if not null; if null,
+ * this will be returned
+ * @param loginContext - If provided, this will be used to log out the user at the appropriate time
*/
- public GenericPrincipal(String name, List<String> roles,
- Principal userPrincipal, LoginContext loginContext) {
+ public GenericPrincipal(String name, List<String> roles, Principal userPrincipal, LoginContext loginContext) {
this(name, roles, userPrincipal, loginContext, null, null);
}
/**
- * Construct a new Principal, associated with the specified Realm, for the
- * specified username, with the specified role names (as Strings).
+ * Construct a new Principal, associated with the specified Realm, for the specified username, with the specified
+ * role names (as Strings).
*
- * @param name The username of the user represented by this Principal
- * @param roles List of roles (must be Strings) possessed by this user
- * @param userPrincipal - the principal to be returned from the request
- * getUserPrincipal call if not null; if null, this will be returned
- * @param loginContext - If provided, this will be used to log out the user
- * at the appropriate time
+ * @param name The username of the user represented by this Principal
+ * @param roles List of roles (must be Strings) possessed by this user
+ * @param userPrincipal - the principal to be returned from the request getUserPrincipal call if not null; if null,
+ * this will be returned
+ * @param loginContext - If provided, this will be used to log out the user at the appropriate time
* @param gssCredential - If provided, the user's delegated credentials
- * @param attributes - If provided, additional attributes associated with
- * this Principal
+ * @param attributes - If provided, additional attributes associated with this Principal
*/
- public GenericPrincipal(String name, List<String> roles,
- Principal userPrincipal, LoginContext loginContext,
+ public GenericPrincipal(String name, List<String> roles, Principal userPrincipal, LoginContext loginContext,
GSSCredential gssCredential, Map<String, Object> attributes) {
super();
this.name = name;
@@ -165,8 +158,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
/**
- * The JAAS LoginContext, if any, used to authenticate this Principal.
- * Kept so we can call logout().
+ * The JAAS LoginContext, if any, used to authenticate this Principal. Kept so we can call logout().
*/
protected final transient LoginContext loginContext;
@@ -180,6 +172,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
public GSSCredential getGssCredential() {
return this.gssCredential;
}
+
protected void setGssCredential(GSSCredential gssCredential) {
this.gssCredential = gssCredential;
}
@@ -197,8 +190,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
*
* @param role Role to be tested
*
- * @return <code>true</code> if this Principal has been assigned the given
- * role, otherwise <code>false</code>
+ * @return <code>true</code> if this Principal has been assigned the given role, otherwise <code>false</code>
*/
public boolean hasRole(String role) {
if ("*".equals(role)) { // Special 2.4 role meaning everyone
@@ -212,8 +204,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
/**
- * Return a String representation of this object, which exposes only
- * information that should be public.
+ * Return a String representation of this object, which exposes only information that should be public.
*/
@Override
public String toString() {
@@ -271,8 +262,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
private final Principal principal;
private final Map<String, Object> attributes;
- public SerializablePrincipal(String name, String[] roles,
- Principal principal, Map<String, Object> attributes) {
+ public SerializablePrincipal(String name, String[] roles, Principal principal, Map<String, Object> attributes) {
this.name = name;
this.roles = roles;
if (principal instanceof Serializable) {
@@ -284,8 +274,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
}
private Object readResolve() {
- return new GenericPrincipal(name, Arrays.asList(roles), principal, null, null,
- attributes);
+ return new GenericPrincipal(name, Arrays.asList(roles), principal, null, null, attributes);
}
}
}
diff --git a/java/org/apache/catalina/realm/JAASCallbackHandler.java b/java/org/apache/catalina/realm/JAASCallbackHandler.java
index dfb3bc6668..bf0205e9b1 100644
--- a/java/org/apache/catalina/realm/JAASCallbackHandler.java
+++ b/java/org/apache/catalina/realm/JAASCallbackHandler.java
@@ -29,17 +29,19 @@ import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.tomcat.util.res.StringManager;
/**
- * <p>Implementation of the JAAS <code>CallbackHandler</code> interface,
- * used to negotiate delivery of the username and credentials that were
- * specified to our constructor. No interaction with the user is required
- * (or possible).</p>
- *
- * <p>This <code>CallbackHandler</code> will pre-digest the supplied
- * password, if required by the <code><Realm></code> element in
- * <code>server.xml</code>.</p>
- * <p>At present, <code>JAASCallbackHandler</code> knows how to handle callbacks of
- * type <code>javax.security.auth.callback.NameCallback</code> and
- * <code>javax.security.auth.callback.PasswordCallback</code>.</p>
+ * <p>
+ * Implementation of the JAAS <code>CallbackHandler</code> interface, used to negotiate delivery of the username and
+ * credentials that were specified to our constructor. No interaction with the user is required (or possible).
+ * </p>
+ * <p>
+ * This <code>CallbackHandler</code> will pre-digest the supplied password, if required by the
+ * <code><Realm></code> element in <code>server.xml</code>.
+ * </p>
+ * <p>
+ * At present, <code>JAASCallbackHandler</code> knows how to handle callbacks of type
+ * <code>javax.security.auth.callback.NameCallback</code> and
+ * <code>javax.security.auth.callback.PasswordCallback</code>.
+ * </p>
*
* @author Craig R. McClanahan
* @author Andrew R. Jaquith
@@ -50,41 +52,35 @@ public class JAASCallbackHandler implements CallbackHandler {
/**
- * Construct a callback handler configured with the specified values.
- * Note that if the <code>JAASRealm</code> instance specifies digested passwords,
- * the <code>password</code> parameter will be pre-digested here.
+ * Construct a callback handler configured with the specified values. Note that if the <code>JAASRealm</code>
+ * instance specifies digested passwords, the <code>password</code> parameter will be pre-digested here.
*
- * @param realm Our associated JAASRealm instance
+ * @param realm Our associated JAASRealm instance
* @param username Username to be authenticated with
* @param password Password to be authenticated with
*/
- public JAASCallbackHandler(JAASRealm realm, String username,
- String password) {
+ public JAASCallbackHandler(JAASRealm realm, String username, String password) {
- this(realm, username, password, null, null, null, null, null, null,
- null);
+ this(realm, username, password, null, null, null, null, null, null, null);
}
/**
* Construct a callback handler for DIGEST authentication.
*
- * @param realm Our associated JAASRealm instance
- * @param username Username to be authenticated with
- * @param password Password to be authenticated with
- * @param nonce Server generated nonce
- * @param nc Nonce count
- * @param cnonce Client generated nonce
- * @param qop Quality of protection applied to the message
- * @param realmName Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest
- * MD5(Method + ":" + uri)
- * @param authMethod The authentication method in use
+ * @param realm Our associated JAASRealm instance
+ * @param username Username to be authenticated with
+ * @param password Password to be authenticated with
+ * @param nonce Server generated nonce
+ * @param nc Nonce count
+ * @param cnonce Client generated nonce
+ * @param qop Quality of protection applied to the message
+ * @param realmName Realm name
+ * @param md5a2 Second MD5 digest used to calculate the digest MD5(Method + ":" + uri)
+ * @param authMethod The authentication method in use
*/
- public JAASCallbackHandler(JAASRealm realm, String username,
- String password, String nonce, String nc,
- String cnonce, String qop, String realmName,
- String md5a2, String authMethod) {
+ public JAASCallbackHandler(JAASRealm realm, String username, String password, String nonce, String nc,
+ String cnonce, String qop, String realmName, String md5a2, String authMethod) {
this.realm = realm;
this.username = username;
@@ -164,21 +160,17 @@ public class JAASCallbackHandler implements CallbackHandler {
/**
- * Retrieve the information requested in the provided <code>Callbacks</code>.
- * This implementation only recognizes {@link NameCallback},
- * {@link PasswordCallback} and {@link TextInputCallback}.
- * {@link TextInputCallback} is used to pass the various additional
- * parameters required for DIGEST authentication.
+ * Retrieve the information requested in the provided <code>Callbacks</code>. This implementation only recognizes
+ * {@link NameCallback}, {@link PasswordCallback} and {@link TextInputCallback}. {@link TextInputCallback} is used
+ * to pass the various additional parameters required for DIGEST authentication.
*
* @param callbacks The set of <code>Callback</code>s to be processed
*
- * @exception IOException if an input/output error occurs
- * @exception UnsupportedCallbackException if the login method requests
- * an unsupported callback type
+ * @exception IOException if an input/output error occurs
+ * @exception UnsupportedCallbackException if the login method requests an unsupported callback type
*/
@Override
- public void handle(Callback callbacks[])
- throws IOException, UnsupportedCallbackException {
+ public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
@@ -187,41 +179,31 @@ public class JAASCallbackHandler implements CallbackHandler {
realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username));
}
((NameCallback) callback).setName(username);
- }
- else if (callback instanceof PasswordCallback) {
+ } else if (callback instanceof PasswordCallback) {
final char[] passwordcontents;
if (password != null) {
passwordcontents = password.toCharArray();
} else {
passwordcontents = new char[0];
}
- ((PasswordCallback) callback).setPassword
- (passwordcontents);
- }
- else if (callback instanceof TextInputCallback) {
+ ((PasswordCallback) callback).setPassword(passwordcontents);
+ } else if (callback instanceof TextInputCallback) {
TextInputCallback cb = ((TextInputCallback) callback);
if (cb.getPrompt().equals("nonce")) {
cb.setText(nonce);
- }
- else if (cb.getPrompt().equals("nc")) {
+ } else if (cb.getPrompt().equals("nc")) {
cb.setText(nc);
- }
- else if (cb.getPrompt().equals("cnonce")) {
+ } else if (cb.getPrompt().equals("cnonce")) {
cb.setText(cnonce);
- }
- else if (cb.getPrompt().equals("qop")) {
+ } else if (cb.getPrompt().equals("qop")) {
cb.setText(qop);
- }
- else if (cb.getPrompt().equals("realmName")) {
+ } else if (cb.getPrompt().equals("realmName")) {
cb.setText(realmName);
- }
- else if (cb.getPrompt().equals("md5a2")) {
+ } else if (cb.getPrompt().equals("md5a2")) {
cb.setText(md5a2);
- }
- else if (cb.getPrompt().equals("authMethod")) {
+ } else if (cb.getPrompt().equals("authMethod")) {
cb.setText(authMethod);
- }
- else if (cb.getPrompt().equals("catalinaBase")) {
+ } else if (cb.getPrompt().equals("catalinaBase")) {
cb.setText(realm.getContainer().getCatalinaBase().getAbsolutePath());
} else {
throw new UnsupportedCallbackException(callback);
diff --git a/java/org/apache/catalina/realm/JAASMemoryLoginModule.java b/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
index d7cdb4a62b..cf9cbab116 100644
--- a/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
+++ b/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
@@ -42,35 +42,30 @@ import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.digester.Digester;
/**
- * <p>Implementation of the JAAS <strong>LoginModule</strong> interface,
- * primarily for use in testing <code>JAASRealm</code>. It utilizes an
- * XML-format data file of username/password/role information identical to
- * that supported by <code>org.apache.catalina.realm.MemoryRealm</code>.</p>
- *
- * <p>This class recognizes the following string-valued options, which are
- * specified in the configuration file and passed to {@link
- * #initialize(Subject, CallbackHandler, Map, Map)} in the <code>options</code>
- * argument:</p>
+ * <p>
+ * Implementation of the JAAS <strong>LoginModule</strong> interface, primarily for use in testing
+ * <code>JAASRealm</code>. It utilizes an XML-format data file of username/password/role information identical to that
+ * supported by <code>org.apache.catalina.realm.MemoryRealm</code>.
+ * </p>
+ * <p>
+ * This class recognizes the following string-valued options, which are specified in the configuration file and passed
+ * to {@link #initialize(Subject, CallbackHandler, Map, Map)} in the <code>options</code> argument:
+ * </p>
* <ul>
- * <li><strong>pathname</strong> - Relative (to the pathname specified by the
- * "catalina.base" system property) or absolute pathname to the
- * XML file containing our user information, in the format supported by
- * {@link MemoryRealm}. The default value matches the MemoryRealm
- * default.</li>
- * <li><strong>credentialHandlerClassName</strong> - The fully qualified class
- * name of the CredentialHandler to use. If not specified, {@link
- * MessageDigestCredentialHandler} will be used.</li>
- * <li>Any additional options will be used to identify and call setters on the
- * {@link CredentialHandler}. For example, <code>algorithm=SHA256</code>
- * would result in a call to {@link
- * MessageDigestCredentialHandler#setAlgorithm(String)} with a parameter of
- * <code>"SHA256"</code></li>
+ * <li><strong>pathname</strong> - Relative (to the pathname specified by the "catalina.base" system property) or
+ * absolute pathname to the XML file containing our user information, in the format supported by {@link MemoryRealm}.
+ * The default value matches the MemoryRealm default.</li>
+ * <li><strong>credentialHandlerClassName</strong> - The fully qualified class name of the CredentialHandler to use. If
+ * not specified, {@link MessageDigestCredentialHandler} will be used.</li>
+ * <li>Any additional options will be used to identify and call setters on the {@link CredentialHandler}. For example,
+ * <code>algorithm=SHA256</code> would result in a call to {@link MessageDigestCredentialHandler#setAlgorithm(String)}
+ * with a parameter of <code>"SHA256"</code></li>
* </ul>
- *
- * <p><strong>IMPLEMENTATION NOTE</strong> - This class implements
- * <code>Realm</code> only to satisfy the calling requirements of the
- * <code>GenericPrincipal</code> constructor. It does not actually perform
- * the functionality required of a <code>Realm</code> implementation.</p>
+ * <p>
+ * <strong>IMPLEMENTATION NOTE</strong> - This class implements <code>Realm</code> only to satisfy the calling
+ * requirements of the <code>GenericPrincipal</code> constructor. It does not actually perform the functionality
+ * required of a <code>Realm</code> implementation.
+ * </p>
*
* @author Craig R. McClanahan
*/
@@ -97,7 +92,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
/**
* The configuration information for this <code>LoginModule</code>.
*/
- protected Map<String,?> options = null;
+ protected Map<String, ?> options = null;
/**
@@ -107,17 +102,15 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
/**
- * The <code>Principal</code> identified by our validation, or
- * <code>null</code> if validation failed.
+ * The <code>Principal</code> identified by our validation, or <code>null</code> if validation failed.
*/
protected Principal principal = null;
/**
- * The state information that is shared with other configured
- * <code>LoginModule</code> instances.
+ * The state information that is shared with other configured <code>LoginModule</code> instances.
*/
- protected Map<String,?> sharedState = null;
+ protected Map<String, ?> sharedState = null;
/**
@@ -135,13 +128,11 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
}
/**
- * Phase 2 of authenticating a <code>Subject</code> when Phase 1
- * fails. This method is called if the <code>LoginContext</code>
- * failed somewhere in the overall authentication chain.
+ * Phase 2 of authenticating a <code>Subject</code> when Phase 1 fails. This method is called if the
+ * <code>LoginContext</code> failed somewhere in the overall authentication chain.
*
- * @return <code>true</code> if this method succeeded, or
- * <code>false</code> if this <code>LoginModule</code> should be
- * ignored
+ * @return <code>true</code> if this method succeeded, or <code>false</code> if this <code>LoginModule</code> should
+ * be ignored
*
* @exception LoginException if the abort fails
*/
@@ -168,13 +159,11 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
/**
- * Phase 2 of authenticating a <code>Subject</code> when Phase 1
- * was successful. This method is called if the <code>LoginContext</code>
- * succeeded in the overall authentication chain.
+ * Phase 2 of authenticating a <code>Subject</code> when Phase 1 was successful. This method is called if the
+ * <code>LoginContext</code> succeeded in the overall authentication chain.
*
- * @return <code>true</code> if the authentication succeeded, or
- * <code>false</code> if this <code>LoginModule</code> should be
- * ignored
+ * @return <code>true</code> if the authentication succeeded, or <code>false</code> if this <code>LoginModule</code>
+ * should be ignored
*
* @exception LoginException if the commit fails
*/
@@ -209,20 +198,16 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
/**
- * Initialize this <code>LoginModule</code> with the specified
- * configuration information.
+ * Initialize this <code>LoginModule</code> with the specified configuration information.
*
- * @param subject The <code>Subject</code> to be authenticated
- * @param callbackHandler A <code>CallbackHandler</code> for communicating
- * with the end user as necessary
- * @param sharedState State information shared with other
- * <code>LoginModule</code> instances
- * @param options Configuration information for this specific
- * <code>LoginModule</code> instance
+ * @param subject The <code>Subject</code> to be authenticated
+ * @param callbackHandler A <code>CallbackHandler</code> for communicating with the end user as necessary
+ * @param sharedState State information shared with other <code>LoginModule</code> instances
+ * @param options Configuration information for this specific <code>LoginModule</code> instance
*/
@Override
- public void initialize(Subject subject, CallbackHandler callbackHandler,
- Map<String,?> sharedState, Map<String,?> options) {
+ public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
+ Map<String, ?> options) {
if (log.isDebugEnabled()) {
log.debug("Init");
}
@@ -253,7 +238,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
credentialHandler = new MessageDigestCredentialHandler();
}
- for (Entry<String,?> entry : options.entrySet()) {
+ for (Entry<String, ?> entry : options.entrySet()) {
if ("pathname".equals(entry.getKey())) {
continue;
}
@@ -263,8 +248,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
// Skip any non-String values since any value we are interested in
// will be a String.
if (entry.getValue() instanceof String) {
- IntrospectionUtils.setProperty(credentialHandler, entry.getKey(),
- (String) entry.getValue());
+ IntrospectionUtils.setProperty(credentialHandler, entry.getKey(), (String) entry.getValue());
}
}
setCredentialHandler(credentialHandler);
@@ -277,9 +261,8 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
/**
* Phase 1 of authenticating a <code>Subject</code>.
*
- * @return <code>true</code> if the authentication succeeded, or
- * <code>false</code> if this <code>LoginModule</code> should be
- * ignored
+ * @return <code>true</code> if the authentication succeeded, or <code>false</code> if this <code>LoginModule</code>
+ * should be ignored
*
* @exception LoginException if the authentication fails
*/
@@ -314,8 +297,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
try {
callbackHandler.handle(callbacks);
username = ((NameCallback) callbacks[0]).getName();
- password =
- new String(((PasswordCallback) callbacks[1]).getPassword());
+ password = new String(((PasswordCallback) callbacks[1]).getPassword());
nonce = ((TextInputCallback) callbacks[2]).getText();
nc = ((TextInputCallback) callbacks[3]).getText();
cnonce = ((TextInputCallback) callbacks[4]).getText();
@@ -332,8 +314,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
// BASIC or FORM
principal = super.authenticate(username, password);
} else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) {
- principal = super.authenticate(username, password, nonce, nc,
- cnonce, qop, realmName, md5a2);
+ principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, md5a2);
} else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) {
principal = super.getPrincipal(username);
} else {
@@ -356,8 +337,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
/**
* Log out this user.
*
- * @return <code>true</code> in all cases because the
- * <code>LoginModule</code> should not be ignored
+ * @return <code>true</code> in all cases because the <code>LoginModule</code> should not be ignored
*
* @exception LoginException if logging out failed
*/
diff --git a/java/org/apache/catalina/realm/JAASRealm.java b/java/org/apache/catalina/realm/JAASRealm.java
index c6b1dcfbfa..4b6dbe3ee7 100644
--- a/java/org/apache/catalina/realm/JAASRealm.java
+++ b/java/org/apache/catalina/realm/JAASRealm.java
@@ -43,61 +43,50 @@ import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
/**
- * <p>Implementation of <b>Realm</b> that authenticates users via the <em>Java
- * Authentication and Authorization Service</em> (JAAS). JAAS support requires
- * either JDK 1.4 (which includes it as part of the standard platform) or
- * JDK 1.3 (with the plug-in <code>jaas.jar</code> file).</p>
- *
- * <p>The value configured for the <code>appName</code> property is passed to
- * the <code>javax.security.auth.login.LoginContext</code> constructor, to
- * specify the <em>application name</em> used to select the set of relevant
- * <code>LoginModules</code> required.</p>
- *
- * <p>The JAAS Specification describes the result of a successful login as a
- * <code>javax.security.auth.Subject</code> instance, which can contain zero
- * or more <code>java.security.Principal</code> objects in the return value
- * of the <code>Subject.getPrincipals()</code> method. However, it provides
- * no guidance on how to distinguish Principals that describe the individual
- * user (and are thus appropriate to return as the value of
- * request.getUserPrincipal() in a web application) from the Principal(s)
- * that describe the authorized roles for this user. To maintain as much
- * independence as possible from the underlying <code>LoginMethod</code>
- * implementation executed by JAAS, the following policy is implemented by
- * this Realm:</p>
+ * <p>
+ * Implementation of <b>Realm</b> that authenticates users via the <em>Java Authentication and Authorization
+ * Service</em> (JAAS). JAAS support requires either JDK 1.4 (which includes it as part of the standard platform) or JDK
+ * 1.3 (with the plug-in <code>jaas.jar</code> file).
+ * </p>
+ * <p>
+ * The value configured for the <code>appName</code> property is passed to the
+ * <code>javax.security.auth.login.LoginContext</code> constructor, to specify the <em>application name</em> used to
+ * select the set of relevant <code>LoginModules</code> required.
+ * </p>
+ * <p>
+ * The JAAS Specification describes the result of a successful login as a <code>javax.security.auth.Subject</code>
+ * instance, which can contain zero or more <code>java.security.Principal</code> objects in the return value of the
+ * <code>Subject.getPrincipals()</code> method. However, it provides no guidance on how to distinguish Principals that
+ * describe the individual user (and are thus appropriate to return as the value of request.getUserPrincipal() in a web
+ * application) from the Principal(s) that describe the authorized roles for this user. To maintain as much independence
+ * as possible from the underlying <code>LoginMethod</code> implementation executed by JAAS, the following policy is
+ * implemented by this Realm:
+ * </p>
* <ul>
- * <li>The JAAS <code>LoginModule</code> is assumed to return a
- * <code>Subject</code> with at least one <code>Principal</code> instance
- * representing the user himself or herself, and zero or more separate
- * <code>Principals</code> representing the security roles authorized
- * for this user.</li>
- * <li>On the <code>Principal</code> representing the user, the Principal
- * name is an appropriate value to return via the Servlet API method
- * <code>HttpServletRequest.getRemoteUser()</code>.</li>
- * <li>On the <code>Principals</code> representing the security roles, the
- * name is the name of the authorized security role.</li>
- * <li>This Realm will be configured with two lists of fully qualified Java
- * class names of classes that implement
- * <code>java.security.Principal</code> - one that identifies class(es)
- * representing a user, and one that identifies class(es) representing
- * a security role.</li>
- * <li>As this Realm iterates over the <code>Principals</code> returned by
- * <code>Subject.getPrincipals()</code>, it will identify the first
- * <code>Principal</code> that matches the "user classes" list as the
- * <code>Principal</code> for this user.</li>
- * <li>As this Realm iterates over the <code>Principals</code> returned by
- * <code>Subject.getPrincipals()</code>, it will accumulate the set of
- * all <code>Principals</code> matching the "role classes" list as
- * identifying the security roles for this user.</li>
- * <li>It is a configuration error for the JAAS login method to return a
- * validated <code>Subject</code> without a <code>Principal</code> that
- * matches the "user classes" list.</li>
- * <li>By default, the enclosing Container's name serves as the
- * application name used to obtain the JAAS LoginContext ("Catalina" in
- * a default installation). Tomcat must be able to find an application
- * with this name in the JAAS configuration file. Here is a hypothetical
- * JAAS configuration file entry for a database-oriented login module that uses
- * a Tomcat-managed JNDI database resource:
- * <blockquote><pre>
+ * <li>The JAAS <code>LoginModule</code> is assumed to return a <code>Subject</code> with at least one
+ * <code>Principal</code> instance representing the user himself or herself, and zero or more separate
+ * <code>Principals</code> representing the security roles authorized for this user.</li>
+ * <li>On the <code>Principal</code> representing the user, the Principal name is an appropriate value to return via the
+ * Servlet API method <code>HttpServletRequest.getRemoteUser()</code>.</li>
+ * <li>On the <code>Principals</code> representing the security roles, the name is the name of the authorized security
+ * role.</li>
+ * <li>This Realm will be configured with two lists of fully qualified Java class names of classes that implement
+ * <code>java.security.Principal</code> - one that identifies class(es) representing a user, and one that identifies
+ * class(es) representing a security role.</li>
+ * <li>As this Realm iterates over the <code>Principals</code> returned by <code>Subject.getPrincipals()</code>, it will
+ * identify the first <code>Principal</code> that matches the "user classes" list as the <code>Principal</code> for this
+ * user.</li>
+ * <li>As this Realm iterates over the <code>Principals</code> returned by <code>Subject.getPrincipals()</code>, it will
+ * accumulate the set of all <code>Principals</code> matching the "role classes" list as identifying the security roles
+ * for this user.</li>
+ * <li>It is a configuration error for the JAAS login method to return a validated <code>Subject</code> without a
+ * <code>Principal</code> that matches the "user classes" list.</li>
+ * <li>By default, the enclosing Container's name serves as the application name used to obtain the JAAS LoginContext
+ * ("Catalina" in a default installation). Tomcat must be able to find an application with this name in the JAAS
+ * configuration file. Here is a hypothetical JAAS configuration file entry for a database-oriented login module that
+ * uses a Tomcat-managed JNDI database resource: <blockquote>
+ *
+ * <pre>
* Catalina {
* org.foobar.auth.DatabaseLoginModule REQUIRED
* JNDI_RESOURCE=jdbc/AuthDB
@@ -109,19 +98,20 @@ import org.apache.tomcat.util.ExceptionUtils;
* ROLE_NAME_COLUMN=name
* PRINCIPAL_FACTORY=org.foobar.auth.impl.SimplePrincipalFactory;
* };
- * </pre></blockquote></li>
- * <li>To set the JAAS configuration file
- * location, set the <code>CATALINA_OPTS</code> environment variable
- * similar to the following:
- * <blockquote><code>CATALINA_OPTS="-Djava.security.auth.login.config=$CATALINA_HOME/conf/jaas.config"</code></blockquote>
+ * </pre>
+ *
+ * </blockquote></li>
+ * <li>To set the JAAS configuration file location, set the <code>CATALINA_OPTS</code> environment variable similar to
+ * the following:
+ * <blockquote><code>CATALINA_OPTS="-Djava.security.auth.login.config=$CATALINA_HOME/conf/jaas.config"</code></blockquote>
* </li>
- * <li>As part of the login process, JAASRealm registers its own <code>CallbackHandler</code>,
- * called (unsurprisingly) <code>JAASCallbackHandler</code>. This handler supplies the
- * HTTP requests's username and credentials to the user-supplied <code>LoginModule</code></li>
- * <li>As with other <code>Realm</code> implementations, digested passwords are supported if
- * the <code><Realm></code> element in <code>server.xml</code> contains a
- * <code>digest</code> attribute; <code>JAASCallbackHandler</code> will digest the password
- * prior to passing it back to the <code>LoginModule</code></li>
+ * <li>As part of the login process, JAASRealm registers its own <code>CallbackHandler</code>, called (unsurprisingly)
+ * <code>JAASCallbackHandler</code>. This handler supplies the HTTP requests's username and credentials to the
+ * user-supplied <code>LoginModule</code></li>
+ * <li>As with other <code>Realm</code> implementations, digested passwords are supported if the
+ * <code><Realm></code> element in <code>server.xml</code> contains a <code>digest</code> attribute;
+ * <code>JAASCallbackHandler</code> will digest the password prior to passing it back to the
+ * <code>LoginModule</code></li>
* </ul>
*
* @author Craig R. McClanahan
@@ -135,8 +125,8 @@ public class JAASRealm extends RealmBase {
/**
- * The application name passed to the JAAS <code>LoginContext</code>,
- * which uses it to select the set of relevant <code>LoginModule</code>s.
+ * The application name passed to the JAAS <code>LoginContext</code>, which uses it to select the set of relevant
+ * <code>LoginModule</code>s.
*/
protected String appName = null;
@@ -154,16 +144,14 @@ public class JAASRealm extends RealmBase {
/**
- * Whether to use context ClassLoader or default ClassLoader.
- * True means use context ClassLoader, and True is the default
- * value.
+ * Whether to use context ClassLoader or default ClassLoader. True means use context ClassLoader, and True is the
+ * default value.
*/
protected boolean useContextClassLoader = true;
/**
- * Path to find a JAAS configuration file, if not set global JVM JAAS
- * configuration will be used.
+ * Path to find a JAAS configuration file, if not set global JVM JAAS configuration will be used.
*/
protected String configFile;
@@ -171,11 +159,10 @@ public class JAASRealm extends RealmBase {
protected volatile boolean jaasConfigurationLoaded = false;
/**
- * Keeps track if JAAS invocation of login modules was successful or not. By
- * default it is true unless we detect JAAS login module can't perform the
- * login. This will be used for realm's {@link #isAvailable()} status so
- * that {@link LockOutRealm} will not lock the user out if JAAS login
- * modules are unavailable to perform the actual login.
+ * Keeps track if JAAS invocation of login modules was successful or not. By default it is true unless we detect
+ * JAAS login module can't perform the login. This will be used for realm's {@link #isAvailable()} status so that
+ * {@link LockOutRealm} will not lock the user out if JAAS login modules are unavailable to perform the actual
+ * login.
*/
private volatile boolean invocationSuccess = true;
@@ -190,6 +177,7 @@ public class JAASRealm extends RealmBase {
/**
* Set the JAAS configuration file.
+ *
* @param configFile The JAAS configuration file
*/
public void setConfigFile(String configFile) {
@@ -198,8 +186,8 @@ public class JAASRealm extends RealmBase {
/**
* Set the JAAS <code>LoginContext</code> app name.
- * @param name The application name that will be used to retrieve
- * the set of relevant <code>LoginModule</code>s
+ *
+ * @param name The application name that will be used to retrieve the set of relevant <code>LoginModule</code>s
*/
public void setAppName(String name) {
appName = name;
@@ -213,8 +201,7 @@ public class JAASRealm extends RealmBase {
}
/**
- * Sets whether to use the context or default ClassLoader.
- * True means use context ClassLoader.
+ * Sets whether to use the context or default ClassLoader. True means use context ClassLoader.
*
* @param useContext True means use context ClassLoader
*/
@@ -223,8 +210,7 @@ public class JAASRealm extends RealmBase {
}
/**
- * Returns whether to use the context or default ClassLoader.
- * True means to use the context ClassLoader.
+ * Returns whether to use the context or default ClassLoader. True means to use the context ClassLoader.
*
* @return The value of useContextClassLoader
*/
@@ -243,8 +229,7 @@ public class JAASRealm extends RealmBase {
}
/**
- * Comma-delimited list of <code>java.security.Principal</code> classes
- * that represent security roles.
+ * Comma-delimited list of <code>java.security.Principal</code> classes that represent security roles.
*/
protected String roleClassNames = null;
@@ -253,10 +238,10 @@ public class JAASRealm extends RealmBase {
}
/**
- * Sets the list of comma-delimited classes that represent roles. The
- * classes in the list must implement <code>java.security.Principal</code>.
- * The supplied list of classes will be parsed when {@link #start()} is
+ * Sets the list of comma-delimited classes that represent roles. The classes in the list must implement
+ * <code>java.security.Principal</code>. The supplied list of classes will be parsed when {@link #start()} is
* called.
+ *
* @param roleClassNames The class names list
*/
public void setRoleClassNames(String roleClassNames) {
@@ -264,13 +249,12 @@ public class JAASRealm extends RealmBase {
}
/**
- * Parses a comma-delimited list of class names, and store the class names
- * in the provided List. Each class must implement
- * <code>java.security.Principal</code>.
+ * Parses a comma-delimited list of class names, and store the class names in the provided List. Each class must
+ * implement <code>java.security.Principal</code>.
*
* @param classNamesString a comma-delimited list of fully qualified class names.
- * @param classNamesList the list in which the class names will be stored.
- * The list is cleared before being populated.
+ * @param classNamesList the list in which the class names will be stored. The list is cleared before being
+ * populated.
*/
protected void parseClassNames(String classNamesString, List<String> classNamesList) {
classNamesList.clear();
@@ -289,8 +273,7 @@ public class JAASRealm extends RealmBase {
continue;
}
try {
- Class<?> principalClass = Class.forName(className, false,
- loader);
+ Class<?> principalClass = Class.forName(className, false, loader);
if (Principal.class.isAssignableFrom(principalClass)) {
classNamesList.add(className);
} else {
@@ -303,8 +286,7 @@ public class JAASRealm extends RealmBase {
}
/**
- * Comma-delimited list of <code>java.security.Principal</code> classes
- * that represent individual users.
+ * Comma-delimited list of <code>java.security.Principal</code> classes that represent individual users.
*/
protected String userClassNames = null;
@@ -313,10 +295,10 @@ public class JAASRealm extends RealmBase {
}
/**
- * Sets the list of comma-delimited classes that represent individual
- * users. The classes in the list must implement
- * <code>java.security.Principal</code>. The supplied list of classes will
- * be parsed when {@link #start()} is called.
+ * Sets the list of comma-delimited classes that represent individual users. The classes in the list must implement
+ * <code>java.security.Principal</code>. The supplied list of classes will be parsed when {@link #start()} is
+ * called.
+ *
* @param userClassNames The class names list
*/
public void setUserClassNames(String userClassNames) {
@@ -327,44 +309,40 @@ public class JAASRealm extends RealmBase {
// --------------------------------------------------------- Public Methods
/**
- * Return the <code>Principal</code> associated with the specified username
- * and credentials, if there is one; otherwise return <code>null</code>.
+ * Return the <code>Principal</code> associated with the specified username and credentials, if there is one;
+ * otherwise return <code>null</code>.
+ *
+ * @param username Username of the <code>Principal</code> to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*
- * @param username Username of the <code>Principal</code> to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
public Principal authenticate(String username, String credentials) {
- return authenticate(username,
- new JAASCallbackHandler(this, username, credentials));
+ return authenticate(username, new JAASCallbackHandler(this, username, credentials));
}
/**
- * Return the <code>Principal</code> associated with the specified username
- * and digest, if there is one; otherwise return <code>null</code>.
+ * Return the <code>Principal</code> associated with the specified username and digest, if there is one; otherwise
+ * return <code>null</code>.
+ *
+ * @param username Username of the <code>Principal</code> to look up
+ * @param clientDigest Digest to use in authenticating this username
+ * @param nonce Server generated nonce
+ * @param nc Nonce count
+ * @param cnonce Client generated nonce
+ * @param qop Quality of protection applied to the message
+ * @param realmName Realm name
+ * @param md5a2 Second MD5 digest used to calculate the digest MD5(Method + ":" + uri)
*
- * @param username Username of the <code>Principal</code> to look up
- * @param clientDigest Digest to use in authenticating this username
- * @param nonce Server generated nonce
- * @param nc Nonce count
- * @param cnonce Client generated nonce
- * @param qop Quality of protection applied to the message
- * @param realmName Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest
- * MD5(Method + ":" + uri)
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
- public Principal authenticate(String username, String clientDigest,
- String nonce, String nc, String cnonce, String qop,
- String realmName, String md5a2) {
- return authenticate(username,
- new JAASCallbackHandler(this, username, clientDigest, nonce,
- nc, cnonce, qop, realmName, md5a2,
- HttpServletRequest.DIGEST_AUTH));
+ public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+ String qop, String realmName, String md5a2) {
+ return authenticate(username, new JAASCallbackHandler(this, username, clientDigest, nonce, nc, cnonce, qop,
+ realmName, md5a2, HttpServletRequest.DIGEST_AUTH));
}
@@ -376,21 +354,22 @@ public class JAASRealm extends RealmBase {
/**
* Perform the actual JAAS authentication.
- * @param username The user name
+ *
+ * @param username The user name
* @param callbackHandler The callback handler
+ *
* @return the associated principal, or <code>null</code> if there is none.
*/
- protected Principal authenticate(String username,
- CallbackHandler callbackHandler) {
+ protected Principal authenticate(String username, CallbackHandler callbackHandler) {
// Establish a LoginContext to use for authentication
try {
LoginContext loginContext = null;
- if( appName==null ) {
- appName="Tomcat";
+ if (appName == null) {
+ appName = "Tomcat";
}
- if( log.isDebugEnabled()) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
}
@@ -399,14 +378,12 @@ public class JAASRealm extends RealmBase {
if (!isUseContextClassLoader()) {
ocl = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(
- this.getClass().getClassLoader());
+ Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
try {
Configuration config = getConfig();
- loginContext = new LoginContext(
- appName, null, callbackHandler, config);
+ loginContext = new LoginContext(appName, null, callbackHandler, config);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("jaasRealm.unexpectedError"), e);
@@ -415,12 +392,12 @@ public class JAASRealm extends RealmBase {
invocationSuccess = false;
return null;
} finally {
- if(!isUseContextClassLoader()) {
+ if (!isUseContextClassLoader()) {
Thread.currentThread().setContextClassLoader(ocl);
}
}
- if( log.isDebugEnabled()) {
+ if (log.isDebugEnabled()) {
log.debug("Login context created " + username);
}
@@ -435,7 +412,7 @@ public class JAASRealm extends RealmBase {
// of the JAAS operation to keep variable consistent.
invocationSuccess = true;
if (subject == null) {
- if( log.isDebugEnabled()) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.failedLogin", username));
}
return null;
@@ -479,7 +456,7 @@ public class JAASRealm extends RealmBase {
return null;
}
- if( log.isDebugEnabled()) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.loginContextCreated", username));
}
@@ -494,9 +471,9 @@ public class JAASRealm extends RealmBase {
}
return principal;
- } catch( Throwable t) {
- log.error( "error ", t);
- //JAAS throws exception different than LoginException so mark the realm as unavailable
+ } catch (Throwable t) {
+ log.error("error ", t);
+ // JAAS throws exception different than LoginException so mark the realm as unavailable
invocationSuccess = false;
return null;
}
@@ -504,9 +481,8 @@ public class JAASRealm extends RealmBase {
/**
- * @return the password associated with the given principal's user name. This
- * always returns null as the JAASRealm has no way of obtaining this
- * information.
+ * @return the password associated with the given principal's user name. This always returns null as the JAASRealm
+ * has no way of obtaining this information.
*/
@Override
protected String getPassword(String username) {
@@ -520,31 +496,27 @@ public class JAASRealm extends RealmBase {
@Override
protected Principal getPrincipal(String username) {
- return authenticate(username,
- new JAASCallbackHandler(this, username, null, null, null, null,
- null, null, null, HttpServletRequest.CLIENT_CERT_AUTH));
+ return authenticate(username, new JAASCallbackHandler(this, username, null, null, null, null, null, null, null,
+ HttpServletRequest.CLIENT_CERT_AUTH));
}
/**
- * Identify and return a <code>java.security.Principal</code> instance
- * representing the authenticated user for the specified <code>Subject</code>.
- * The Principal is constructed by scanning the list of Principals returned
- * by the JAASLoginModule. The first <code>Principal</code> object that matches
- * one of the class names supplied as a "user class" is the user Principal.
- * This object is returned to the caller.
- * Any remaining principal objects returned by the LoginModules are mapped to
- * roles, but only if their respective classes match one of the "role class" classes.
+ * Identify and return a <code>java.security.Principal</code> instance representing the authenticated user for the
+ * specified <code>Subject</code>. The Principal is constructed by scanning the list of Principals returned by the
+ * JAASLoginModule. The first <code>Principal</code> object that matches one of the class names supplied as a "user
+ * class" is the user Principal. This object is returned to the caller. Any remaining principal objects returned by
+ * the LoginModules are mapped to roles, but only if their respective classes match one of the "role class" classes.
* If a user Principal cannot be constructed, return <code>null</code>.
- * @param username The associated user name
- * @param subject The <code>Subject</code> representing the logged-in user
- * @param loginContext Associated with the Principal so
- * {@link LoginContext#logout()} can be called later
+ *
+ * @param username The associated user name
+ * @param subject The <code>Subject</code> representing the logged-in user
+ * @param loginContext Associated with the Principal so {@link LoginContext#logout()} can be called later
+ *
* @return the principal object
*/
- protected Principal createPrincipal(String username, Subject subject,
- LoginContext loginContext) {
+ protected Principal createPrincipal(String username, Subject subject, LoginContext loginContext) {
// Prepare to scan the Principals for this Subject
List<String> roles = new ArrayList<>();
@@ -554,20 +526,20 @@ public class JAASRealm extends RealmBase {
for (Principal principal : subject.getPrincipals()) {
String principalClass = principal.getClass().getName();
- if( log.isDebugEnabled() ) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.checkPrincipal", principal, principalClass));
}
if (userPrincipal == null && userClasses.contains(principalClass)) {
userPrincipal = principal;
- if( log.isDebugEnabled() ) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.userPrincipalSuccess", principal.getName()));
}
}
if (roleClasses.contains(principalClass)) {
roles.add(principal.getName());
- if( log.isDebugEnabled() ) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.rolePrincipalAdd", principal.getName()));
}
}
@@ -589,30 +561,28 @@ public class JAASRealm extends RealmBase {
}
// Return the resulting Principal for our authenticated user
- return new GenericPrincipal(username, roles, userPrincipal,
- loginContext);
+ return new GenericPrincipal(username, roles, userPrincipal, loginContext);
}
/**
- * Ensure the given name is legal for JAAS configuration.
- * Added for Bugzilla 30869, made protected for easy customization
- * in case my implementation is insufficient, which I think is
- * very likely.
+ * Ensure the given name is legal for JAAS configuration. Added for Bugzilla 30869, made protected for easy
+ * customization in case my implementation is insufficient, which I think is very likely.
*
* @param src The name to validate
+ *
* @return A string that's a valid JAAS realm name
*/
protected String makeLegalForJAAS(final String src) {
String result = src;
// Default name is "other" per JAAS spec
- if(result == null) {
+ if (result == null) {
result = "other";
}
// Strip leading slash if present, as Sun JAAS impl
// barfs on it (see Bugzilla 30869 bug report).
- if(result.startsWith("/")) {
+ if (result.startsWith("/")) {
result = result.substring(1);
}
@@ -624,12 +594,11 @@ public class JAASRealm extends RealmBase {
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected void startInternal() throws LifecycleException {
@@ -645,6 +614,7 @@ public class JAASRealm extends RealmBase {
/**
* Load custom JAAS Configuration.
+ *
* @return the loaded configuration
*/
protected Configuration getConfig() {
@@ -662,10 +632,9 @@ public class JAASRealm extends RealmBase {
URL resource = Thread.currentThread().getContextClassLoader().getResource(configFile);
URI uri = resource.toURI();
@SuppressWarnings("unchecked")
- Class<Configuration> sunConfigFile = (Class<Configuration>)
- Class.forName("com.sun.security.auth.login.ConfigFile");
- Constructor<Configuration> constructor =
- sunConfigFile.getConstructor(URI.class);
+ Class<Configuration> sunConfigFile = (Class<Configuration>) Class
+ .forName("com.sun.security.auth.login.ConfigFile");
+ Constructor<Configuration> constructor = sunConfigFile.getConstructor(URI.class);
Configuration config = constructor.newInstance(uri);
this.jaasConfiguration = config;
this.jaasConfigurationLoaded = true;
@@ -673,8 +642,7 @@ public class JAASRealm extends RealmBase {
}
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
- } catch (SecurityException | URISyntaxException | ReflectiveOperationException |
- IllegalArgumentException ex) {
+ } catch (SecurityException | URISyntaxException | ReflectiveOperationException | IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
}
diff --git a/java/org/apache/catalina/realm/JNDIRealm.java b/java/org/apache/catalina/realm/JNDIRealm.java
index 7ab15ec76f..7fd80ede50 100644
--- a/java/org/apache/catalina/realm/JNDIRealm.java
+++ b/java/org/apache/catalina/realm/JNDIRealm.java
@@ -70,113 +70,76 @@ import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSName;
/**
- * <p>Implementation of <strong>Realm</strong> that works with a directory
- * server accessed via the Java Naming and Directory Interface (JNDI) APIs.
- * The following constraints are imposed on the data structure in the
- * underlying directory server:</p>
+ * <p>
+ * Implementation of <strong>Realm</strong> that works with a directory server accessed via the Java Naming and
+ * Directory Interface (JNDI) APIs. The following constraints are imposed on the data structure in the underlying
+ * directory server:
+ * </p>
* <ul>
- *
- * <li>Each user that can be authenticated is represented by an individual
- * element in the top level <code>DirContext</code> that is accessed
- * via the <code>connectionURL</code> property.</li>
- *
- * <li>If a socket connection cannot be made to the <code>connectURL</code>
- * an attempt will be made to use the <code>alternateURL</code> if it
- * exists.</li>
- *
- * <li>Each user element has a distinguished name that can be formed by
- * substituting the presented username into a pattern configured by the
- * <code>userPattern</code> property.</li>
- *
- * <li>Alternatively, if the <code>userPattern</code> property is not
- * specified, a unique element can be located by searching the directory
- * context. In this case:
- * <ul>
- * <li>The <code>userSearch</code> pattern specifies the search filter
- * after substitution of the username.</li>
- * <li>The <code>userBase</code> property can be set to the element that
- * is the base of the subtree containing users. If not specified,
- * the search base is the top-level context.</li>
- * <li>The <code>userSubtree</code> property can be set to
- * <code>true</code> if you wish to search the entire subtree of the
- * directory context. The default value of <code>false</code>
- * requests a search of only the current level.</li>
- * </ul>
+ * <li>Each user that can be authenticated is represented by an individual element in the top level
+ * <code>DirContext</code> that is accessed via the <code>connectionURL</code> property.</li>
+ * <li>If a socket connection cannot be made to the <code>connectURL</code> an attempt will be made to use the
+ * <code>alternateURL</code> if it exists.</li>
+ * <li>Each user element has a distinguished name that can be formed by substituting the presented username into a
+ * pattern configured by the <code>userPattern</code> property.</li>
+ * <li>Alternatively, if the <code>userPattern</code> property is not specified, a unique element can be located by
+ * searching the directory context. In this case:
+ * <ul>
+ * <li>The <code>userSearch</code> pattern specifies the search filter after substitution of the username.</li>
+ * <li>The <code>userBase</code> property can be set to the element that is the base of the subtree containing users. If
+ * not specified, the search base is the top-level context.</li>
+ * <li>The <code>userSubtree</code> property can be set to <code>true</code> if you wish to search the entire subtree of
+ * the directory context. The default value of <code>false</code> requests a search of only the current level.</li>
+ * </ul>
* </li>
- *
- * <li>The user may be authenticated by binding to the directory with the
- * username and password presented. This method is used when the
- * <code>userPassword</code> property is not specified.</li>
- *
- * <li>The user may be authenticated by retrieving the value of an attribute
- * from the directory and comparing it explicitly with the value presented
- * by the user. This method is used when the <code>userPassword</code>
- * property is specified, in which case:
- * <ul>
- * <li>The element for this user must contain an attribute named by the
- * <code>userPassword</code> property.
- * <li>The value of the user password attribute is either a cleartext
- * String, or the result of passing a cleartext String through the
- * <code>RealmBase.digest()</code> method (using the standard digest
- * support included in <code>RealmBase</code>).
- * <li>The user is considered to be authenticated if the presented
- * credentials (after being passed through
- * <code>RealmBase.digest()</code>) are equal to the retrieved value
- * for the user password attribute.</li>
- * </ul></li>
- *
- * <li>Each group of users that has been assigned a particular role may be
- * represented by an individual element in the top level
- * <code>DirContext</code> that is accessed via the
- * <code>connectionURL</code> property. This element has the following
- * characteristics:
- * <ul>
- * <li>The set of all possible groups of interest can be selected by a
- * search pattern configured by the <code>roleSearch</code>
- * property.</li>
- * <li>The <code>roleSearch</code> pattern optionally includes pattern
- * replacements "{0}" for the distinguished name, and/or "{1}" for
- * the username, and/or "{2}" the value of an attribute from the
- * user's directory entry (the attribute is specified by the
- * <code>userRoleAttribute</code> property), of the authenticated user
- * for which roles will be retrieved.</li>
- * <li>The <code>roleBase</code> property can be set to the element that
- * is the base of the search for matching roles. If not specified,
- * the entire context will be searched.</li>
- * <li>The <code>roleSubtree</code> property can be set to
- * <code>true</code> if you wish to search the entire subtree of the
- * directory context. The default value of <code>false</code>
- * requests a search of only the current level.</li>
- * <li>The element includes an attribute (whose name is configured by
- * the <code>roleName</code> property) containing the name of the
- * role represented by this element.</li>
- * </ul></li>
- *
- * <li>In addition, roles may be represented by the values of an attribute
- * in the user's element whose name is configured by the
- * <code>userRoleName</code> property.</li>
- *
- * <li>A default role can be assigned to each user that was successfully
- * authenticated by setting the <code>commonRole</code> property to the
- * name of this role. The role doesn't have to exist in the directory.</li>
- *
- * <li>If the directory server contains nested roles, you can search for them
- * by setting <code>roleNested</code> to <code>true</code>.
- * The default value is <code>false</code>, so role searches will not find
- * nested roles.</li>
- *
- * <li>Note that the standard <code><security-role-ref></code> element in
- * the web application deployment descriptor allows applications to refer
- * to roles programmatically by names other than those used in the
- * directory server itself.</li>
+ * <li>The user may be authenticated by binding to the directory with the username and password presented. This method
+ * is used when the <code>userPassword</code> property is not specified.</li>
+ * <li>The user may be authenticated by retrieving the value of an attribute from the directory and comparing it
+ * explicitly with the value presented by the user. This method is used when the <code>userPassword</code> property is
+ * specified, in which case:
+ * <ul>
+ * <li>The element for this user must contain an attribute named by the <code>userPassword</code> property.
+ * <li>The value of the user password attribute is either a cleartext String, or the result of passing a cleartext
+ * String through the <code>RealmBase.digest()</code> method (using the standard digest support included in
+ * <code>RealmBase</code>).
+ * <li>The user is considered to be authenticated if the presented credentials (after being passed through
+ * <code>RealmBase.digest()</code>) are equal to the retrieved value for the user password attribute.</li>
* </ul>
- *
- * <p><strong>WARNING</strong> - There is a reported bug against the Netscape
- * provider code (com.netscape.jndi.ldap.LdapContextFactory) with respect to
- * successfully authenticated a non-existing user. The
- * report is here: https://bz.apache.org/bugzilla/show_bug.cgi?id=11210 .
- * With luck, Netscape has updated their provider code and this is not an
- * issue. </p>
+ * </li>
+ * <li>Each group of users that has been assigned a particular role may be represented by an individual element in the
+ * top level <code>DirContext</code> that is accessed via the <code>connectionURL</code> property. This element has the
+ * following characteristics:
+ * <ul>
+ * <li>The set of all possible groups of interest can be selected by a search pattern configured by the
+ * <code>roleSearch</code> property.</li>
+ * <li>The <code>roleSearch</code> pattern optionally includes pattern replacements "{0}" for the distinguished name,
+ * and/or "{1}" for the username, and/or "{2}" the value of an attribute from the user's directory entry (the attribute
+ * is specified by the <code>userRoleAttribute</code> property), of the authenticated user for which roles will be
+ * retrieved.</li>
+ * <li>The <code>roleBase</code> property can be set to the element that is the base of the search for matching roles.
+ * If not specified, the entire context will be searched.</li>
+ * <li>The <code>roleSubtree</code> property can be set to <code>true</code> if you wish to search the entire subtree of
+ * the directory context. The default value of <code>false</code> requests a search of only the current level.</li>
+ * <li>The element includes an attribute (whose name is configured by the <code>roleName</code> property) containing the
+ * name of the role represented by this element.</li>
+ * </ul>
+ * </li>
+ * <li>In addition, roles may be represented by the values of an attribute in the user's element whose name is
+ * configured by the <code>userRoleName</code> property.</li>
+ * <li>A default role can be assigned to each user that was successfully authenticated by setting the
+ * <code>commonRole</code> property to the name of this role. The role doesn't have to exist in the directory.</li>
+ * <li>If the directory server contains nested roles, you can search for them by setting <code>roleNested</code> to
+ * <code>true</code>. The default value is <code>false</code>, so role searches will not find nested roles.</li>
+ * <li>Note that the standard <code><security-role-ref></code> element in the web application deployment
+ * descriptor allows applications to refer to roles programmatically by names other than those used in the directory
+ * server itself.</li>
+ * </ul>
+ * <p>
+ * <strong>WARNING</strong> - There is a reported bug against the Netscape provider code
+ * (com.netscape.jndi.ldap.LdapContextFactory) with respect to successfully authenticated a non-existing user. The
+ * report is here: https://bz.apache.org/bugzilla/show_bug.cgi?id=11210 . With luck, Netscape has updated their provider
+ * code and this is not an issue.
+ * </p>
*
* @author John Holman
* @author Craig R. McClanahan
@@ -186,7 +149,7 @@ public class JNDIRealm extends RealmBase {
// ----------------------------------------------------- Instance Variables
/**
- * The type of authentication to use
+ * The type of authentication to use
*/
protected String authentication = null;
@@ -206,9 +169,8 @@ public class JNDIRealm extends RealmBase {
protected String connectionURL = null;
/**
- * The JNDI context factory used to acquire our InitialContext. By
- * default, assumes use of an LDAP server using the standard JNDI LDAP
- * provider.
+ * The JNDI context factory used to acquire our InitialContext. By default, assumes use of an LDAP server using the
+ * standard JNDI LDAP provider.
*/
protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
@@ -218,31 +180,27 @@ public class JNDIRealm extends RealmBase {
protected String derefAliases = null;
/**
- * Constant that holds the name of the environment property for specifying
- * the manner in which aliases should be dereferenced.
+ * Constant that holds the name of the environment property for specifying the manner in which aliases should be
+ * dereferenced.
*/
public static final String DEREF_ALIASES = "java.naming.ldap.derefAliases";
/**
- * The protocol that will be used in the communication with the
- * directory server.
+ * The protocol that will be used in the communication with the directory server.
*/
protected String protocol = null;
/**
- * Should we ignore PartialResultExceptions when iterating over NamingEnumerations?
- * Microsoft Active Directory often returns referrals, which lead
- * to PartialResultExceptions. Unfortunately there's no stable way to detect,
- * if the Exceptions really come from an AD referral.
- * Set to true to ignore PartialResultExceptions.
+ * Should we ignore PartialResultExceptions when iterating over NamingEnumerations? Microsoft Active Directory often
+ * returns referrals, which lead to PartialResultExceptions. Unfortunately there's no stable way to detect, if the
+ * Exceptions really come from an AD referral. Set to true to ignore PartialResultExceptions.
*/
protected boolean adCompat = false;
/**
- * How should we handle referrals? Microsoft Active Directory often returns
- * referrals. If you need to follow them set referrals to "follow".
- * Caution: if your DNS is not part of AD, the LDAP client lib might try
- * to resolve your domain name in DNS to find another LDAP server.
+ * How should we handle referrals? Microsoft Active Directory often returns referrals. If you need to follow them
+ * set referrals to "follow". Caution: if your DNS is not part of AD, the LDAP client lib might try to resolve your
+ * domain name in DNS to find another LDAP server.
*/
protected String referrals = null;
@@ -252,16 +210,14 @@ public class JNDIRealm extends RealmBase {
protected String userBase = "";
/**
- * The message format used to search for a user, with "{0}" marking
- * the spot where the username goes.
+ * The message format used to search for a user, with "{0}" marking the spot where the username goes.
*/
protected String userSearch = null;
/**
- * When searching for users, should the search be performed as the user
- * currently being authenticated? If false, {@link #connectionName} and
- * {@link #connectionPassword} will be used if specified, else an anonymous
- * connection will be used.
+ * When searching for users, should the search be performed as the user currently being authenticated? If false,
+ * {@link #connectionName} and {@link #connectionPassword} will be used if specified, else an anonymous connection
+ * will be used.
*/
private boolean userSearchAsUser = false;
@@ -276,27 +232,21 @@ public class JNDIRealm extends RealmBase {
protected String userPassword = null;
/**
- * The name of the attribute inside the users
- * directory entry where the value will be
- * taken to search for roles
- * This attribute is not used during a nested search
+ * The name of the attribute inside the users directory entry where the value will be taken to search for roles This
+ * attribute is not used during a nested search
*/
protected String userRoleAttribute = null;
/**
- * A string of LDAP user patterns or paths, ":"-separated
- * These will be used to form the distinguished name of a
- * user, with "{0}" marking the spot where the specified username
- * goes.
- * This is similar to userPattern, but allows for multiple searches
- * for a user.
+ * A string of LDAP user patterns or paths, ":"-separated These will be used to form the distinguished name of a
+ * user, with "{0}" marking the spot where the specified username goes. This is similar to userPattern, but allows
+ * for multiple searches for a user.
*/
protected String[] userPatternArray = null;
/**
- * The message format used to form the distinguished name of a
- * user, with "{0}" marking the spot where the specified username
- * goes.
+ * The message format used to form the distinguished name of a user, with "{0}" marking the spot where the specified
+ * username goes.
*/
protected String userPattern = null;
@@ -306,8 +256,7 @@ public class JNDIRealm extends RealmBase {
protected String roleBase = "";
/**
- * The name of an attribute in the user's entry containing
- * roles for that user
+ * The name of an attribute in the user's entry containing roles for that user
*/
protected String userRoleName = null;
@@ -317,9 +266,8 @@ public class JNDIRealm extends RealmBase {
protected String roleName = null;
/**
- * The message format used to select roles for a user, with "{0}" marking
- * the spot where the distinguished name of the user goes. The "{1}"
- * and "{2}" are described in the Configuration Reference.
+ * The message format used to select roles for a user, with "{0}" marking the spot where the distinguished name of
+ * the user goes. The "{1}" and "{2}" are described in the Configuration Reference.
*/
protected String roleSearch = null;
@@ -334,9 +282,8 @@ public class JNDIRealm extends RealmBase {
protected boolean roleNested = false;
/**
- * When searching for user roles, should the search be performed as the user
- * currently being authenticated? If false, {@link #connectionName} and
- * {@link #connectionPassword} will be used if specified, else an anonymous
+ * When searching for user roles, should the search be performed as the user currently being authenticated? If
+ * false, {@link #connectionName} and {@link #connectionPassword} will be used if specified, else an anonymous
* connection will be used.
*/
protected boolean roleSearchAsUser = false;
@@ -347,51 +294,46 @@ public class JNDIRealm extends RealmBase {
protected String alternateURL;
/**
- * The number of connection attempts. If greater than zero we use the
- * alternate url.
+ * The number of connection attempts. If greater than zero we use the alternate url.
*/
protected int connectionAttempt = 0;
/**
- * Add this role to every authenticated user
+ * Add this role to every authenticated user
*/
protected String commonRole = null;
/**
- * The timeout, in milliseconds, to use when trying to create a connection
- * to the directory. The default is 5000 (5 seconds).
+ * The timeout, in milliseconds, to use when trying to create a connection to the directory. The default is 5000 (5
+ * seconds).
*/
protected String connectionTimeout = "5000";
/**
- * The timeout, in milliseconds, to use when trying to read from a connection
- * to the directory. The default is 5000 (5 seconds).
+ * The timeout, in milliseconds, to use when trying to read from a connection to the directory. The default is 5000
+ * (5 seconds).
*/
protected String readTimeout = "5000";
/**
- * The sizeLimit (also known as the countLimit) to use when the realm is
- * configured with {@link #userSearch}. Zero for no limit.
+ * The sizeLimit (also known as the countLimit) to use when the realm is configured with {@link #userSearch}. Zero
+ * for no limit.
*/
protected long sizeLimit = 0;
/**
- * The timeLimit (in milliseconds) to use when the realm is configured with
- * {@link #userSearch}. Zero for no limit.
+ * The timeLimit (in milliseconds) to use when the realm is configured with {@link #userSearch}. Zero for no limit.
*/
protected int timeLimit = 0;
/**
- * Should delegated credentials from the SPNEGO authenticator be used if
- * available
+ * Should delegated credentials from the SPNEGO authenticator be used if available
*/
protected boolean useDelegatedCredential = true;
/**
- * The QOP that should be used for the connection to the LDAP server after
- * authentication. This value is used to set the
- * <code>javax.security.sasl.qop</code> environment property for the LDAP
- * connection.
+ * The QOP that should be used for the connection to the LDAP server after authentication. This value is used to set
+ * the <code>javax.security.sasl.qop</code> environment property for the LDAP connection.
*/
protected String spnegoDelegationQop = "auth-conf";
@@ -403,14 +345,13 @@ public class JNDIRealm extends RealmBase {
private StartTlsResponse tls = null;
/**
- * The list of enabled cipher suites used for establishing tls connections.
- * <code>null</code> means to use the default cipher suites.
+ * The list of enabled cipher suites used for establishing tls connections. <code>null</code> means to use the
+ * default cipher suites.
*/
private String[] cipherSuitesArray = null;
/**
- * Verifier for hostnames in a StartTLS secured connection. <code>null</code>
- * means to use the default verifier.
+ * Verifier for hostnames in a StartTLS secured connection. <code>null</code> means to use the default verifier.
*/
private HostnameVerifier hostnameVerifier = null;
@@ -420,20 +361,17 @@ public class JNDIRealm extends RealmBase {
private SSLSocketFactory sslSocketFactory = null;
/**
- * Name of the class of the {@link SSLSocketFactory}. <code>null</code>
- * means to use the default factory.
+ * Name of the class of the {@link SSLSocketFactory}. <code>null</code> means to use the default factory.
*/
private String sslSocketFactoryClassName;
/**
- * Comma separated list of cipher suites to use for StartTLS. If empty, the
- * default suites are used.
+ * Comma separated list of cipher suites to use for StartTLS. If empty, the default suites are used.
*/
private String cipherSuites;
/**
- * Name of the class of the {@link HostnameVerifier}. <code>null</code>
- * means to use the default verifier.
+ * Name of the class of the {@link HostnameVerifier}. <code>null</code> means to use the default verifier.
*/
private String hostNameVerifierClassName;
@@ -465,9 +403,8 @@ public class JNDIRealm extends RealmBase {
protected int connectionPoolSize = 1;
/**
- * Whether to use context ClassLoader or default ClassLoader.
- * True means use context ClassLoader, and True is the default
- * value.
+ * Whether to use context ClassLoader or default ClassLoader. True means use context ClassLoader, and True is the
+ * default value.
*/
protected boolean useContextClassLoader = true;
@@ -613,17 +550,17 @@ public class JNDIRealm extends RealmBase {
/**
* @return the current settings for handling PartialResultExceptions
*/
- public boolean getAdCompat () {
+ public boolean getAdCompat() {
return adCompat;
}
/**
- * How do we handle PartialResultExceptions?
- * True: ignore all PartialResultExceptions.
+ * How do we handle PartialResultExceptions? True: ignore all PartialResultExceptions.
+ *
* @param adCompat <code>true</code> to ignore partial results
*/
- public void setAdCompat (boolean adCompat) {
+ public void setAdCompat(boolean adCompat) {
this.adCompat = adCompat;
}
@@ -631,17 +568,18 @@ public class JNDIRealm extends RealmBase {
/**
* @return the current settings for handling JNDI referrals.
*/
- public String getReferrals () {
+ public String getReferrals() {
return referrals;
}
/**
- * How do we handle JNDI referrals? ignore, follow, or throw
- * (see javax.naming.Context.REFERRAL for more information).
+ * How do we handle JNDI referrals? ignore, follow, or throw (see javax.naming.Context.REFERRAL for more
+ * information).
+ *
* @param referrals The referral handling
*/
- public void setReferrals (String referrals) {
+ public void setReferrals(String referrals) {
this.referrals = referrals;
}
@@ -867,12 +805,10 @@ public class JNDIRealm extends RealmBase {
/**
- * Set the message format pattern for selecting users in this Realm.
- * This may be one simple pattern, or multiple patterns to be tried,
- * separated by parentheses. (for example, either "cn={0}", or
- * "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported,
- * but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is
- * also valid. Complex search strings with &, etc are NOT supported.
+ * Set the message format pattern for selecting users in this Realm. This may be one simple pattern, or multiple
+ * patterns to be tried, separated by parentheses. (for example, either "cn={0}", or "(cn={0})(cn={0},o=myorg)" Full
+ * LDAP search strings are also supported, but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is also
+ * valid. Complex search strings with &, etc are NOT supported.
*
* @param userPattern The new user pattern
*/
@@ -1012,9 +948,7 @@ public class JNDIRealm extends RealmBase {
/**
* Flag whether StartTLS should be used when connecting to the ldap server
*
- * @param useStartTls
- * {@code true} when StartTLS should be used. Default is
- * {@code false}.
+ * @param useStartTls {@code true} when StartTLS should be used. Default is {@code false}.
*/
public void setUseStartTls(boolean useStartTls) {
this.useStartTls = useStartTls;
@@ -1022,8 +956,7 @@ public class JNDIRealm extends RealmBase {
/**
- * @return list of the allowed cipher suites when connections are made using
- * StartTLS
+ * @return list of the allowed cipher suites when connections are made using StartTLS
*/
private String[] getCipherSuitesArray() {
if (cipherSuites == null || cipherSuitesArray != null) {
@@ -1034,19 +967,17 @@ public class JNDIRealm extends RealmBase {
this.cipherSuitesArray = null;
} else {
this.cipherSuitesArray = cipherSuites.trim().split("\\s*,\\s*");
- containerLog.debug(sm.getString("jndiRealm.cipherSuites",
- Arrays.toString(this.cipherSuitesArray)));
+ containerLog.debug(sm.getString("jndiRealm.cipherSuites", Arrays.toString(this.cipherSuitesArray)));
}
return this.cipherSuitesArray;
}
/**
- * Set the allowed cipher suites when opening a connection using StartTLS.
- * The cipher suites are expected as a comma separated list.
+ * Set the allowed cipher suites when opening a connection using StartTLS. The cipher suites are expected as a comma
+ * separated list.
*
- * @param suites
- * comma separated list of allowed cipher suites
+ * @param suites comma separated list of allowed cipher suites
*/
public void setCipherSuites(String suites) {
this.cipherSuites = suites;
@@ -1054,8 +985,7 @@ public class JNDIRealm extends RealmBase {
/**
- * @return the connection pool size, or the default value 1 if pooling
- * is disabled
+ * @return the connection pool size, or the default value 1 if pooling is disabled
*/
public int getConnectionPoolSize() {
return connectionPoolSize;
@@ -1064,6 +994,7 @@ public class JNDIRealm extends RealmBase {
/**
* Set the connection pool size
+ *
* @param connectionPoolSize the new pool size
*/
public void setConnectionPoolSize(int connectionPoolSize) {
@@ -1072,9 +1003,8 @@ public class JNDIRealm extends RealmBase {
/**
- * @return name of the {@link HostnameVerifier} class used for connections
- * using StartTLS, or the empty string, if the default verifier
- * should be used.
+ * @return name of the {@link HostnameVerifier} class used for connections using StartTLS, or the empty string, if
+ * the default verifier should be used.
*/
public String getHostnameVerifierClassName() {
if (this.hostnameVerifier == null) {
@@ -1085,12 +1015,10 @@ public class JNDIRealm extends RealmBase {
/**
- * Set the {@link HostnameVerifier} to be used when opening connections
- * using StartTLS. An instance of the given class name will be constructed
- * using the default constructor.
+ * Set the {@link HostnameVerifier} to be used when opening connections using StartTLS. An instance of the given
+ * class name will be constructed using the default constructor.
*
- * @param verifierClassName
- * class name of the {@link HostnameVerifier} to be constructed
+ * @param verifierClassName class name of the {@link HostnameVerifier} to be constructed
*/
public void setHostnameVerifierClassName(String verifierClassName) {
if (verifierClassName != null) {
@@ -1102,8 +1030,8 @@ public class JNDIRealm extends RealmBase {
/**
- * @return the {@link HostnameVerifier} to use for peer certificate
- * verification when opening connections using StartTLS.
+ * @return the {@link HostnameVerifier} to use for peer certificate verification when opening connections using
+ * StartTLS.
*/
public HostnameVerifier getHostnameVerifier() {
if (this.hostnameVerifier != null) {
@@ -1118,26 +1046,22 @@ public class JNDIRealm extends RealmBase {
this.hostnameVerifier = (HostnameVerifier) o;
return this.hostnameVerifier;
} else {
- throw new IllegalArgumentException(sm.getString(
- "jndiRealm.invalidHostnameVerifier",
- hostNameVerifierClassName));
+ throw new IllegalArgumentException(
+ sm.getString("jndiRealm.invalidHostnameVerifier", hostNameVerifierClassName));
}
} catch (ReflectiveOperationException | SecurityException e) {
- throw new IllegalArgumentException(sm.getString(
- "jndiRealm.invalidHostnameVerifier",
- hostNameVerifierClassName), e);
+ throw new IllegalArgumentException(
+ sm.getString("jndiRealm.invalidHostnameVerifier", hostNameVerifierClassName), e);
}
}
/**
- * Set the {@link SSLSocketFactory} to be used when opening connections
- * using StartTLS. An instance of the factory with the given name will be
- * created using the default constructor. The SSLSocketFactory can also be
- * set using {@link JNDIRealm#setSslProtocol(String) setSslProtocol(String)}.
+ * Set the {@link SSLSocketFactory} to be used when opening connections using StartTLS. An instance of the factory
+ * with the given name will be created using the default constructor. The SSLSocketFactory can also be set using
+ * {@link JNDIRealm#setSslProtocol(String) setSslProtocol(String)}.
*
- * @param factoryClassName
- * class name of the factory to be constructed
+ * @param factoryClassName class name of the factory to be constructed
*/
public void setSslSocketFactoryClassName(String factoryClassName) {
this.sslSocketFactoryClassName = factoryClassName;
@@ -1147,8 +1071,7 @@ public class JNDIRealm extends RealmBase {
/**
* Set the ssl protocol to be used for connections using StartTLS.
*
- * @param protocol
- * one of the allowed ssl protocol names
+ * @param protocol one of the allowed ssl protocol names
*/
public void setSslProtocol(String protocol) {
this.sslProtocol = protocol;
@@ -1156,8 +1079,7 @@ public class JNDIRealm extends RealmBase {
/**
- * @return the list of supported ssl protocols by the default
- * {@link SSLContext}
+ * @return the list of supported ssl protocols by the default {@link SSLContext}
*/
private String[] getSupportedSslProtocols() {
try {
@@ -1169,16 +1091,14 @@ public class JNDIRealm extends RealmBase {
}
- private Object constructInstance(String className)
- throws ReflectiveOperationException {
+ private Object constructInstance(String className) throws ReflectiveOperationException {
Class<?> clazz = Class.forName(className);
return clazz.getConstructor().newInstance();
}
/**
- * Sets whether to use the context or default ClassLoader.
- * True means use context ClassLoader.
+ * Sets whether to use the context or default ClassLoader. True means use context ClassLoader.
*
* @param useContext True means use context ClassLoader
*/
@@ -1188,8 +1108,7 @@ public class JNDIRealm extends RealmBase {
/**
- * Returns whether to use the context or default ClassLoader.
- * True means to use the context ClassLoader.
+ * Returns whether to use the context or default ClassLoader. True means to use the context ClassLoader.
*
* @return The value of useContextClassLoader
*/
@@ -1201,17 +1120,14 @@ public class JNDIRealm extends RealmBase {
// ---------------------------------------------------------- Realm Methods
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>. If there are any errors with the JDBC connection, executing the query or anything we return
+ * null (don't authenticate). This event is also logged, and the connection will be closed so that a subsequent
+ * request will automatically re-open it.
*
- * If there are any errors with the JDBC connection, executing
- * the query or anything we return null (don't authenticate). This
- * event is also logged, and the connection will be closed so that
- * a subsequent request will automatically re-open it.
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
@@ -1236,7 +1152,7 @@ public class JNDIRealm extends RealmBase {
try {
- // Occasionally the directory context will timeout. Try one more
+ // Occasionally the directory context will timeout. Try one more
// time before giving up.
// Authenticate the specified username if possible
@@ -1244,18 +1160,14 @@ public class JNDIRealm extends RealmBase {
} catch (NullPointerException | NamingException e) {
/*
- * BZ 61313
- * NamingException may or may not indicate an error that is
- * recoverable via fail over. Therefore a decision needs to be
- * made whether to fail over or not. Generally, attempting to
- * fail over when it is not appropriate is better than not
- * failing over when it is appropriate so the code always
+ * BZ 61313 NamingException may or may not indicate an error that is recoverable via fail over.
+ * Therefore a decision needs to be made whether to fail over or not. Generally, attempting to fail over
+ * when it is not appropriate is better than not failing over when it is appropriate so the code always
* attempts to fail over for NamingExceptions.
*/
/*
- * BZ 42449
- * Catch NPE - Kludge Sun's LDAP provider with broken SSL.
+ * BZ 42449 Catch NPE - Kludge Sun's LDAP provider with broken SSL.
*/
// log the exception so we know it's there.
@@ -1302,13 +1214,13 @@ public class JNDIRealm extends RealmBase {
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>.
+ *
+ * @param connection The directory context
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*
- * @param connection The directory context
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*
* @exception NamingException if a directory server error occurs
@@ -1390,10 +1302,8 @@ public class JNDIRealm extends RealmBase {
/*
- * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
- * This method can be removed and the class loader switch moved back to
- * open() once it is known that Tomcat must be running on a JVM that
- * includes a fix for
+ * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+ * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
* https://bugs.openjdk.java.net/browse/JDK-8273874
*/
@Override
@@ -1414,15 +1324,13 @@ public class JNDIRealm extends RealmBase {
/*
- * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
- * This method can be removed and the class loader switch moved back to
- * open() once it is known that Tomcat must be running on a JVM that
- * includes a fix for
+ * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+ * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
* https://bugs.openjdk.java.net/browse/JDK-8273874
*/
@Override
- public Principal authenticate(String username, String clientDigest, String nonce, String nc,
- String cnonce, String qop, String realm, String md5a2) {
+ public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+ String qop, String realm, String md5a2) {
ClassLoader ocl = null;
try {
if (!isUseContextClassLoader()) {
@@ -1439,10 +1347,8 @@ public class JNDIRealm extends RealmBase {
/*
- * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
- * This method can be removed and the class loader switch moved back to
- * open() once it is known that Tomcat must be running on a JVM that
- * includes a fix for
+ * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+ * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
* https://bugs.openjdk.java.net/browse/JDK-8273874
*/
@Override
@@ -1463,10 +1369,8 @@ public class JNDIRealm extends RealmBase {
/*
- * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
- * This method can be removed and the class loader switch moved back to
- * open() once it is known that Tomcat must be running on a JVM that
- * includes a fix for
+ * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+ * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
* https://bugs.openjdk.java.net/browse/JDK-8273874
*/
@Override
@@ -1487,10 +1391,8 @@ public class JNDIRealm extends RealmBase {
/*
- * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
- * This method can be removed and the class loader switch moved back to
- * open() once it is known that Tomcat must be running on a JVM that
- * includes a fix for
+ * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+ * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
* https://bugs.openjdk.java.net/browse/JDK-8273874
*/
@Override
@@ -1513,13 +1415,14 @@ public class JNDIRealm extends RealmBase {
// ------------------------------------------------------ Protected Methods
/**
- * Return a User object containing information about the user
- * with the specified username, if found in the directory;
- * otherwise return <code>null</code>.
+ * Return a User object containing information about the user with the specified username, if found in the
+ * directory; otherwise return <code>null</code>.
*
* @param connection The directory context
- * @param username Username to be looked up
+ * @param username Username to be looked up
+ *
* @return the User object
+ *
* @exception NamingException if a directory server error occurs
*
* @see #getUser(JNDIConnection, String, String, int)
@@ -1530,14 +1433,15 @@ public class JNDIRealm extends RealmBase {
/**
- * Return a User object containing information about the user
- * with the specified username, if found in the directory;
- * otherwise return <code>null</code>.
+ * Return a User object containing information about the user with the specified username, if found in the
+ * directory; otherwise return <code>null</code>.
*
- * @param connection The directory context
- * @param username Username to be looked up
+ * @param connection The directory context
+ * @param username Username to be looked up
* @param credentials User credentials (optional)
+ *
* @return the User object
+ *
* @exception NamingException if a directory server error occurs
*
* @see #getUser(JNDIConnection, String, String, int)
@@ -1548,21 +1452,19 @@ public class JNDIRealm extends RealmBase {
/**
- * Return a User object containing information about the user
- * with the specified username, if found in the directory;
- * otherwise return <code>null</code>.
+ * Return a User object containing information about the user with the specified username, if found in the
+ * directory; otherwise return <code>null</code>. If the <code>userPassword</code> configuration attribute is
+ * specified, the value of that attribute is retrieved from the user's directory entry. If the
+ * <code>userRoleName</code> configuration attribute is specified, all values of that attribute are retrieved from
+ * the directory entry.
*
- * If the <code>userPassword</code> configuration attribute is
- * specified, the value of that attribute is retrieved from the
- * user's directory entry. If the <code>userRoleName</code>
- * configuration attribute is specified, all values of that
- * attribute are retrieved from the directory entry.
- *
- * @param connection The directory context
- * @param username Username to be looked up
- * @param credentials User credentials (optional)
+ * @param connection The directory context
+ * @param username Username to be looked up
+ * @param credentials User credentials (optional)
* @param curUserPattern Index into userPatternFormatArray
+ *
* @return the User object
+ *
* @exception NamingException if a directory server error occurs
*/
protected User getUser(JNDIConnection connection, String username, String credentials, int curUserPattern)
@@ -1616,16 +1518,16 @@ public class JNDIRealm extends RealmBase {
/**
- * Use the distinguished name to locate the directory
- * entry for the user with the specified username and
- * return a User object; otherwise return <code>null</code>.
+ * Use the distinguished name to locate the directory entry for the user with the specified username and return a
+ * User object; otherwise return <code>null</code>.
*
- * @param context The directory context
+ * @param context The directory context
* @param username The username
- * @param attrIds String[]containing names of attributes to
- * @param dn Distinguished name of the user
- * retrieve.
+ * @param attrIds String[]containing names of attributes to
+ * @param dn Distinguished name of the user retrieve.
+ *
* @return the User object
+ *
* @exception NamingException if a directory server error occurs
*/
protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn)
@@ -1633,7 +1535,7 @@ public class JNDIRealm extends RealmBase {
// If no attributes are requested, no need to look for them
if (attrIds == null || attrIds.length == 0) {
- return new User(username, dn, null, null,null);
+ return new User(username, dn, null, null, null);
}
// Get required attributes from user entry
@@ -1669,18 +1571,19 @@ public class JNDIRealm extends RealmBase {
/**
- * Use the <code>UserPattern</code> configuration attribute to
- * locate the directory entry for the user with the specified
- * username and return a User object; otherwise return
- * <code>null</code>.
+ * Use the <code>UserPattern</code> configuration attribute to locate the directory entry for the user with the
+ * specified username and return a User object; otherwise return <code>null</code>.
*
- * @param connection The directory context
- * @param username The username
- * @param credentials User credentials (optional)
- * @param attrIds String[]containing names of attributes to
+ * @param connection The directory context
+ * @param username The username
+ * @param credentials User credentials (optional)
+ * @param attrIds String[]containing names of attributes to
* @param curUserPattern Index into userPatternFormatArray
+ *
* @return the User object
+ *
* @exception NamingException if a directory server error occurs
+ *
* @see #getUserByPattern(DirContext, String, String[], String)
*/
protected User getUserByPattern(JNDIConnection connection, String username, String credentials, String[] attrIds,
@@ -1695,8 +1598,8 @@ public class JNDIRealm extends RealmBase {
// Form the DistinguishedName from the user pattern.
// Escape in case username contains a character with special meaning in
// an attribute value.
- String dn = connection.userPatternFormatArray[curUserPattern].format(
- new String[] { doAttributeValueEscaping(username) });
+ String dn = connection.userPatternFormatArray[curUserPattern]
+ .format(new String[] { doAttributeValueEscaping(username) });
try {
user = getUserByPattern(connection.context, username, attrIds, dn);
@@ -1718,14 +1621,15 @@ public class JNDIRealm extends RealmBase {
/**
- * Search the directory to return a User object containing
- * information about the user with the specified username, if
- * found in the directory; otherwise return <code>null</code>.
+ * Search the directory to return a User object containing information about the user with the specified username,
+ * if found in the directory; otherwise return <code>null</code>.
*
* @param connection The directory context
- * @param username The username
- * @param attrIds String[]containing names of attributes to retrieve.
+ * @param username The username
+ * @param attrIds String[]containing names of attributes to retrieve.
+ *
* @return the User object
+ *
* @exception NamingException if a directory server error occurs
*/
protected User getUserBySearch(JNDIConnection connection, String username, String[] attrIds)
@@ -1830,18 +1734,17 @@ public class JNDIRealm extends RealmBase {
/**
- * Check whether the given User can be authenticated with the
- * given credentials. If the <code>userPassword</code>
- * configuration attribute is specified, the credentials
- * previously retrieved from the directory are compared explicitly
- * with those presented by the user. Otherwise the presented
- * credentials are checked by binding to the directory as the
- * user.
+ * Check whether the given User can be authenticated with the given credentials. If the <code>userPassword</code>
+ * configuration attribute is specified, the credentials previously retrieved from the directory are compared
+ * explicitly with those presented by the user. Otherwise the presented credentials are checked by binding to the
+ * directory as the user.
*
- * @param context The directory context
- * @param user The User to be authenticated
+ * @param context The directory context
+ * @param user The User to be authenticated
* @param credentials The credentials presented by the user
+ *
* @return <code>true</code> if the credentials are validated
+ *
* @exception NamingException if a directory server error occurs
*/
protected boolean checkCredentials(DirContext context, User user, String credentials) throws NamingException {
@@ -1866,13 +1769,14 @@ public class JNDIRealm extends RealmBase {
/**
- * Check whether the credentials presented by the user match those
- * retrieved from the directory.
+ * Check whether the credentials presented by the user match those retrieved from the directory.
*
- * @param context The directory context
- * @param info The User to be authenticated
+ * @param context The directory context
+ * @param info The User to be authenticated
* @param credentials Authentication credentials
+ *
* @return <code>true</code> if the credentials are validated
+ *
* @exception NamingException if a directory server error occurs
*/
protected boolean compareCredentials(DirContext context, User info, String credentials) throws NamingException {
@@ -1894,10 +1798,12 @@ public class JNDIRealm extends RealmBase {
/**
* Check credentials by binding to the directory as the user
*
- * @param context The directory context
- * @param user The User to be authenticated
+ * @param context The directory context
+ * @param user The User to be authenticated
* @param credentials Authentication credentials
+ *
* @return <code>true</code> if the credentials are validated
+ *
* @exception NamingException if a directory server error occurs
*/
protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException {
@@ -1924,12 +1830,11 @@ public class JNDIRealm extends RealmBase {
boolean validated = false;
try {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(" binding as " + dn);
+ containerLog.trace(" binding as " + dn);
}
context.getAttributes("", null);
validated = true;
- }
- catch (AuthenticationException e) {
+ } catch (AuthenticationException e) {
if (containerLog.isTraceEnabled()) {
containerLog.trace(" bind attempt failed");
}
@@ -1942,12 +1847,12 @@ public class JNDIRealm extends RealmBase {
/**
- * Configure the context to use the provided credentials for
- * authentication.
+ * Configure the context to use the provided credentials for authentication.
+ *
+ * @param context DirContext to configure
+ * @param dn Distinguished name of user
+ * @param credentials Credentials of user
*
- * @param context DirContext to configure
- * @param dn Distinguished name of user
- * @param credentials Credentials of user
* @exception NamingException if a directory server error occurs
*/
private void userCredentialsAdd(DirContext context, String dn, String credentials) throws NamingException {
@@ -1958,11 +1863,11 @@ public class JNDIRealm extends RealmBase {
/**
- * Configure the context to use {@link #connectionName} and
- * {@link #connectionPassword} if specified or an anonymous connection if
- * those attributes are not specified.
+ * Configure the context to use {@link #connectionName} and {@link #connectionPassword} if specified or an anonymous
+ * connection if those attributes are not specified.
+ *
+ * @param context DirContext to configure
*
- * @param context DirContext to configure
* @exception NamingException if a directory server error occurs
*/
private void userCredentialsRemove(DirContext context) throws NamingException {
@@ -1982,14 +1887,14 @@ public class JNDIRealm extends RealmBase {
/**
- * Return a List of roles associated with the given User. Any
- * roles present in the user's directory entry are supplemented by
- * a directory search. If no roles are associated with this user,
- * a zero-length List is returned.
+ * Return a List of roles associated with the given User. Any roles present in the user's directory entry are
+ * supplemented by a directory search. If no roles are associated with this user, a zero-length List is returned.
*
* @param connection The directory context we are searching
- * @param user The User to be checked
+ * @param user The User to be checked
+ *
* @return the list of role names
+ *
* @exception NamingException if a directory server error occurs
*/
protected List<String> getRoles(JNDIConnection connection, User user) throws NamingException {
@@ -2037,17 +1942,16 @@ public class JNDIRealm extends RealmBase {
// Set up parameters for an appropriate search filter
// The dn is already attribute value escaped but the others are not
// This is a filter so all input will require filter escaping
- String filter = connection.roleFormat.format(new String[] {
- doFilterEscaping(dn),
- doFilterEscaping(doAttributeValueEscaping(username)),
- doFilterEscaping(doAttributeValueEscaping(userRoleId)) });
+ String filter = connection.roleFormat
+ .format(new String[] { doFilterEscaping(dn), doFilterEscaping(doAttributeValueEscaping(username)),
+ doFilterEscaping(doAttributeValueEscaping(userRoleId)) });
SearchControls controls = new SearchControls();
if (roleSubtree) {
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
- controls.setReturningAttributes(new String[] {roleName});
+ controls.setReturningAttributes(new String[] { roleName });
String base = null;
if (connection.roleBaseFormat != null) {
@@ -2057,7 +1961,7 @@ public class JNDIRealm extends RealmBase {
for (int i = 0; i < name.size(); i++) {
// May have been returned with \<char> escaping rather than
// \<hex><hex>. Make sure it is \<hex><hex>.
- nameParts[i] = convertToHexEscape(name.get(i));
+ nameParts[i] = convertToHexEscape(name.get(i));
}
base = connection.roleBaseFormat.format(nameParts);
} else {
@@ -2069,7 +1973,7 @@ public class JNDIRealm extends RealmBase {
isRoleSearchAsUser());
if (results == null) {
- return list; // Should never happen, but just in case ...
+ return list; // Should never happen, but just in case ...
}
Map<String, String> groupMap = new HashMap<>();
@@ -2098,7 +2002,7 @@ public class JNDIRealm extends RealmBase {
Set<Entry<String, String>> entries = groupMap.entrySet();
containerLog.trace(" Found " + entries.size() + " direct roles");
for (Entry<String, String> entry : entries) {
- containerLog.trace( " Found direct role " + entry.getKey() + " -> " + entry.getValue());
+ containerLog.trace(" Found direct role " + entry.getKey() + " -> " + entry.getValue());
}
}
@@ -2117,14 +2021,13 @@ public class JNDIRealm extends RealmBase {
// Group key is already value escaped if required
// Group value is not value escaped
// Everything needs to be filter escaped
- filter = connection.roleFormat.format(new String[] {
- doFilterEscaping(group.getKey()),
+ filter = connection.roleFormat.format(new String[] { doFilterEscaping(group.getKey()),
doFilterEscaping(doAttributeValueEscaping(group.getValue())),
doFilterEscaping(doAttributeValueEscaping(group.getValue())) });
if (containerLog.isTraceEnabled()) {
- containerLog.trace("Perform a nested group search with base "+ roleBase +
- " and filter " + filter);
+ containerLog
+ .trace("Perform a nested group search with base " + roleBase + " and filter " + filter);
}
results = searchAsUser(connection.context, user, base, filter, controls, isRoleSearchAsUser());
@@ -2166,26 +2069,20 @@ public class JNDIRealm extends RealmBase {
/**
- * Perform the search on the context as the {@code dn}, when
- * {@code searchAsUser} is {@code true}, otherwise search the context with
- * the default credentials.
+ * Perform the search on the context as the {@code dn}, when {@code searchAsUser} is {@code true}, otherwise search
+ * the context with the default credentials.
+ *
+ * @param context context to search on
+ * @param user user to bind on
+ * @param base base to start the search from
+ * @param filter filter to use for the search
+ * @param controls controls to use for the search
+ * @param searchAsUser {@code true} when the search should be done as user, or {@code false} for using the default
+ * credentials
*
- * @param context
- * context to search on
- * @param user
- * user to bind on
- * @param base
- * base to start the search from
- * @param filter
- * filter to use for the search
- * @param controls
- * controls to use for the search
- * @param searchAsUser
- * {@code true} when the search should be done as user, or
- * {@code false} for using the default credentials
* @return enumeration with all found entries
- * @throws NamingException
- * if a directory server error occurs
+ *
+ * @throws NamingException if a directory server error occurs
*/
private NamingEnumeration<SearchResult> searchAsUser(DirContext context, User user, String base, String filter,
SearchControls controls, boolean searchAsUser) throws NamingException {
@@ -2208,8 +2105,10 @@ public class JNDIRealm extends RealmBase {
* Return a String representing the value of the specified attribute.
*
* @param attrId Attribute name
- * @param attrs Attributes containing the required value
+ * @param attrs Attributes containing the required value
+ *
* @return the attribute value
+ *
* @exception NamingException if a directory server error occurs
*/
private String getAttributeValue(String attrId, Attributes attrs) throws NamingException {
@@ -2245,9 +2144,11 @@ public class JNDIRealm extends RealmBase {
* Add values of a specified attribute to a list
*
* @param attrId Attribute name
- * @param attrs Attributes containing the new values
+ * @param attrs Attributes containing the new values
* @param values ArrayList containing values found so far
+ *
* @return the list of attribute values
+ *
* @exception NamingException if a directory server error occurs
*/
private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values)
@@ -2268,8 +2169,8 @@ public class JNDIRealm extends RealmBase {
}
NamingEnumeration<?> e = attr.getAll();
try {
- while(e.hasMore()) {
- String value = (String)e.next();
+ while (e.hasMore()) {
+ String value = (String) e.next();
values.add(value);
}
} catch (PartialResultException ex) {
@@ -2341,7 +2242,9 @@ public class JNDIRealm extends RealmBase {
/**
* Get the password for the specified user.
+ *
* @param username The user name
+ *
* @return the password associated with the given principal's user name.
*/
@Override
@@ -2357,7 +2260,7 @@ public class JNDIRealm extends RealmBase {
// Ensure that we have a directory context available
connection = get();
- // Occasionally the directory context will timeout. Try one more
+ // Occasionally the directory context will timeout. Try one more
// time before giving up.
try {
user = getUser(connection, username, null);
@@ -2399,7 +2302,9 @@ public class JNDIRealm extends RealmBase {
/**
* Get the principal associated with the specified certificate.
+ *
* @param username The user name
+ *
* @return the Principal associated with the given certificate.
*/
@Override
@@ -2433,7 +2338,7 @@ public class JNDIRealm extends RealmBase {
// Ensure that we have a directory context available
connection = get();
- // Occasionally the directory context will timeout. Try one more
+ // Occasionally the directory context will timeout. Try one more
// time before giving up.
try {
@@ -2477,10 +2382,13 @@ public class JNDIRealm extends RealmBase {
/**
* Get the principal associated with the specified certificate.
- * @param connection The directory context
- * @param username The user name
+ *
+ * @param connection The directory context
+ * @param username The user name
* @param gssCredential The credentials
+ *
* @return the Principal associated with the given certificate.
+ *
* @exception NamingException if a directory server error occurs
*/
protected Principal getPrincipal(JNDIConnection connection, String username, GSSCredential gssCredential)
@@ -2500,7 +2408,7 @@ public class JNDIRealm extends RealmBase {
context.addToEnvironment("javax.security.sasl.server.authentication", "true");
context.addToEnvironment("javax.security.sasl.qop", spnegoDelegationQop);
// Note: Subject already set in SPNEGO authenticator so no need
- // for Subject.doAs() here
+ // for Subject.doAs() here
}
user = getUser(connection, username);
if (user != null) {
@@ -2522,13 +2430,12 @@ public class JNDIRealm extends RealmBase {
}
- private void restoreEnvironmentParameter(DirContext context,
- String parameterName, Hashtable<?, ?> preservedEnvironment) {
+ private void restoreEnvironmentParameter(DirContext context, String parameterName,
+ Hashtable<?, ?> preservedEnvironment) {
try {
context.removeFromEnvironment(parameterName);
if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) {
- context.addToEnvironment(parameterName,
- preservedEnvironment.get(parameterName));
+ context.addToEnvironment(parameterName, preservedEnvironment.get(parameterName));
}
} catch (NamingException e) {
// Ignore
@@ -2537,9 +2444,10 @@ public class JNDIRealm extends RealmBase {
/**
- * Open (if necessary) and return a connection to the configured
- * directory server for this Realm.
+ * Open (if necessary) and return a connection to the configured directory server for this Realm.
+ *
* @return the connection
+ *
* @exception NamingException if a directory server error occurs
*/
protected JNDIConnection get() throws NamingException {
@@ -2584,8 +2492,8 @@ public class JNDIRealm extends RealmBase {
/**
- * Create a new connection wrapper, along with the
- * message formats.
+ * Create a new connection wrapper, along with the message formats.
+ *
* @return the new connection
*/
protected JNDIConnection create() {
@@ -2595,7 +2503,9 @@ public class JNDIRealm extends RealmBase {
/**
* Create a new connection to the directory server.
+ *
* @param connection The directory server connection wrapper
+ *
* @throws NamingException if a directory server error occurs
*/
protected void open(JNDIConnection connection) throws NamingException {
@@ -2657,14 +2567,10 @@ public class JNDIRealm extends RealmBase {
if (o instanceof SSLSocketFactory) {
return sslSocketFactory;
} else {
- throw new IllegalArgumentException(sm.getString(
- "jndiRealm.invalidSslSocketFactory",
- className));
+ throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslSocketFactory", className));
}
} catch (ReflectiveOperationException | SecurityException e) {
- throw new IllegalArgumentException(sm.getString(
- "jndiRealm.invalidSslSocketFactory",
- className), e);
+ throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslSocketFactory", className), e);
}
}
@@ -2681,21 +2587,20 @@ public class JNDIRealm extends RealmBase {
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
List<String> allowedProtocols = Arrays.asList(getSupportedSslProtocols());
- throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslProtocol",
- protocol, allowedProtocols), e);
+ throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslProtocol", protocol, allowedProtocols),
+ e);
}
}
/**
- * Create a tls enabled LdapContext and set the StartTlsResponse tls
- * instance variable.
+ * Create a tls enabled LdapContext and set the StartTlsResponse tls instance variable.
+ *
+ * @param env Environment to use for context creation
*
- * @param env
- * Environment to use for context creation
* @return configured {@link LdapContext}
- * @throws NamingException
- * when something goes wrong while negotiating the connection
+ *
+ * @throws NamingException when something goes wrong while negotiating the connection
*/
private DirContext createTlsDirContext(Hashtable<String, String> env) throws NamingException {
Map<String, Object> savedEnv = new HashMap<>();
@@ -2738,9 +2643,9 @@ public class JNDIRealm extends RealmBase {
*
* @return java.util.Hashtable the configuration for the directory context.
*/
- protected Hashtable<String,String> getDirectoryContextEnvironment() {
+ protected Hashtable<String, String> getDirectoryContextEnvironment() {
- Hashtable<String,String> env = new Hashtable<>();
+ Hashtable<String, String> env = new Hashtable<>();
// Configure our directory context environment.
if (containerLog.isDebugEnabled() && connectionAttempt == 0) {
@@ -2786,12 +2691,11 @@ public class JNDIRealm extends RealmBase {
// ------------------------------------------------------ Lifecycle Methods
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected void startInternal() throws LifecycleException {
@@ -2831,12 +2735,10 @@ public class JNDIRealm extends RealmBase {
/**
- * Gracefully terminate the active use of the public methods of this
- * component and implement the requirements of
+ * Gracefully terminate the active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
+ * @exception LifecycleException if this component detects a fatal error that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
@@ -2853,13 +2755,12 @@ public class JNDIRealm extends RealmBase {
/**
- * Given a string containing LDAP patterns for user locations (separated by
- * parentheses in a pseudo-LDAP search string format -
- * "(location1)(location2)", returns an array of those paths. Real LDAP
- * search strings are supported as well (though only the "|" "OR" type).
+ * Given a string containing LDAP patterns for user locations (separated by parentheses in a pseudo-LDAP search
+ * string format - "(location1)(location2)", returns an array of those paths. Real LDAP search strings are supported
+ * as well (though only the "|" "OR" type).
+ *
+ * @param userPatternString - a string LDAP search paths surrounded by parentheses
*
- * @param userPatternString - a string LDAP search paths surrounded by
- * parentheses
* @return a parsed string array
*/
protected String[] parseUserPatternString(String userPatternString) {
@@ -2869,7 +2770,7 @@ public class JNDIRealm extends RealmBase {
int startParenLoc = userPatternString.indexOf('(');
if (startParenLoc == -1) {
// no parens here; return whole thing
- return new String[] {userPatternString};
+ return new String[] { userPatternString };
}
int startingPoint = 0;
while (startParenLoc > -1) {
@@ -2877,18 +2778,18 @@ public class JNDIRealm extends RealmBase {
// weed out escaped open parens and parens enclosing the
// whole statement (in the case of valid LDAP search
// strings: (|(something)(somethingelse))
- while ( (userPatternString.charAt(startParenLoc + 1) == '|') ||
- (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\') ) {
- startParenLoc = userPatternString.indexOf('(', startParenLoc+1);
+ while ((userPatternString.charAt(startParenLoc + 1) == '|') ||
+ (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\')) {
+ startParenLoc = userPatternString.indexOf('(', startParenLoc + 1);
}
- endParenLoc = userPatternString.indexOf(')', startParenLoc+1);
+ endParenLoc = userPatternString.indexOf(')', startParenLoc + 1);
// weed out escaped end-parens
while (userPatternString.charAt(endParenLoc - 1) == '\\') {
- endParenLoc = userPatternString.indexOf(')', endParenLoc+1);
+ endParenLoc = userPatternString.indexOf(')', endParenLoc + 1);
}
- String nextPathPart = userPatternString.substring(startParenLoc+1, endParenLoc);
+ String nextPathPart = userPatternString.substring(startParenLoc + 1, endParenLoc);
pathList.add(nextPathPart);
- startingPoint = endParenLoc+1;
+ startingPoint = endParenLoc + 1;
startParenLoc = userPatternString.indexOf('(', startingPoint);
}
return pathList.toArray(new String[0]);
@@ -2898,16 +2799,9 @@ public class JNDIRealm extends RealmBase {
/**
- * Given an LDAP search string, returns the string with certain characters
- * escaped according to RFC 2254 guidelines.
- * The character mapping is as follows:
- * char -> Replacement
- * ---------------------------
- * * -> \2a
- * ( -> \28
- * ) -> \29
- * \ -> \5c
- * \0 -> \00
+ * Given an LDAP search string, returns the string with certain characters escaped according to RFC 2254 guidelines.
+ * The character mapping is as follows: char -> Replacement --------------------------- * -> \2a ( -> \28 )
+ * -> \29 \ -> \5c \0 -> \00
*
* @param inString string to escape according to RFC 2254 guidelines
*
@@ -2949,15 +2843,17 @@ public class JNDIRealm extends RealmBase {
* Returns the distinguished name of a search result.
*
* @param context Our DirContext
- * @param base The base DN
- * @param result The search result
+ * @param base The base DN
+ * @param result The search result
+ *
* @return String containing the distinguished name
+ *
* @exception NamingException if a directory server error occurs
*/
protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException {
- // Get the entry's distinguished name. For relative results, this means
+ // Get the entry's distinguished name. For relative results, this means
// we need to composite a name with the base name, the context name, and
- // the result name. For non-relative names, use the returned name.
+ // the result name. For non-relative names, use the returned name.
String resultName = result.getName();
Name name;
if (result.isRelative()) {
@@ -2983,11 +2879,11 @@ public class JNDIRealm extends RealmBase {
URI userNameUri = new URI(resultName);
String pathComponent = userNameUri.getPath();
// Should not ever have an empty path component, since that is /{DN}
- if (pathComponent.length() < 1 ) {
+ if (pathComponent.length() < 1) {
throw new InvalidNameException("Search returned unparseable absolute name: " + resultName);
}
name = parser.parse(pathComponent.substring(1));
- } catch ( URISyntaxException e ) {
+ } catch (URISyntaxException e) {
throw new InvalidNameException("Search returned unparseable absolute name: " + resultName);
}
}
@@ -3002,11 +2898,11 @@ public class JNDIRealm extends RealmBase {
/**
- * Implements the necessary escaping to represent an attribute value as a
- * String as per RFC 4514.
+ * Implements the necessary escaping to represent an attribute value as a String as per RFC 4514.
*
* @param input The original attribute value
- * @return The string representation of the attribute value
+ *
+ * @return The string representation of the attribute value
*/
protected String doAttributeValueEscaping(String input) {
if (input == null) {
@@ -3019,7 +2915,7 @@ public class JNDIRealm extends RealmBase {
char c = input.charAt(i);
switch (c) {
case ' ': {
- if (i == 0 || i == (len -1)) {
+ if (i == 0 || i == (len - 1)) {
result.append("\\20");
} else {
result.append(c);
@@ -3027,7 +2923,7 @@ public class JNDIRealm extends RealmBase {
break;
}
case '#': {
- if (i == 0 ) {
+ if (i == 0) {
result.append("\\23");
} else {
result.append(c);
@@ -3200,34 +3096,29 @@ public class JNDIRealm extends RealmBase {
/**
- * Class holding the connection to the directory plus the associated
- * non thread safe message formats.
+ * Class holding the connection to the directory plus the associated non thread safe message formats.
*/
protected static class JNDIConnection {
/**
- * The MessageFormat object associated with the current
- * <code>userSearch</code>.
+ * The MessageFormat object associated with the current <code>userSearch</code>.
*/
public final MessageFormat userSearchFormat;
/**
- * An array of MessageFormat objects associated with the current
- * <code>userPatternArray</code>.
+ * An array of MessageFormat objects associated with the current <code>userPatternArray</code>.
*/
public final MessageFormat[] userPatternFormatArray;
/**
- * The MessageFormat object associated with the current
- * <code>roleBase</code>.
+ * The MessageFormat object associated with the current <code>roleBase</code>.
*/
public final MessageFormat roleBaseFormat;
/**
- * The MessageFormat object associated with the current
- * <code>roleSearch</code>.
+ * The MessageFormat object associated with the current <code>roleSearch</code>.
*/
- public final MessageFormat roleFormat ;
+ public final MessageFormat roleFormat;
/**
* The directory context linking us to our directory server.
diff --git a/java/org/apache/catalina/realm/LockOutRealm.java b/java/org/apache/catalina/realm/LockOutRealm.java
index f4254dcb64..ab09da9811 100644
--- a/java/org/apache/catalina/realm/LockOutRealm.java
+++ b/java/org/apache/catalina/realm/LockOutRealm.java
@@ -31,80 +31,70 @@ import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSName;
/**
- * This class extends the CombinedRealm (hence it can wrap other Realms) to
- * provide a user lock out mechanism if there are too many failed
- * authentication attempts in a given period of time. To ensure correct
- * operation, there is a reasonable degree of synchronisation in this Realm.
- * This Realm does not require modification to the underlying Realms or the
- * associated user storage mechanisms. It achieves this by recording all failed
- * logins, including those for users that do not exist. To prevent a DOS by
- * deliberating making requests with invalid users (and hence causing this cache
- * to grow) the size of the list of users that have failed authentication is
- * limited.
+ * This class extends the CombinedRealm (hence it can wrap other Realms) to provide a user lock out mechanism if there
+ * are too many failed authentication attempts in a given period of time. To ensure correct operation, there is a
+ * reasonable degree of synchronisation in this Realm. This Realm does not require modification to the underlying Realms
+ * or the associated user storage mechanisms. It achieves this by recording all failed logins, including those for users
+ * that do not exist. To prevent a DOS by deliberating making requests with invalid users (and hence causing this cache
+ * to grow) the size of the list of users that have failed authentication is limited.
*/
public class LockOutRealm extends CombinedRealm {
private static final Log log = LogFactory.getLog(LockOutRealm.class);
/**
- * The number of times in a row a user has to fail authentication to be
- * locked out. Defaults to 5.
+ * The number of times in a row a user has to fail authentication to be locked out. Defaults to 5.
*/
protected int failureCount = 5;
/**
- * The time (in seconds) a user is locked out for after too many
- * authentication failures. Defaults to 300 (5 minutes).
+ * The time (in seconds) a user is locked out for after too many authentication failures. Defaults to 300 (5
+ * minutes).
*/
protected int lockOutTime = 300;
/**
- * Number of users that have failed authentication to keep in cache. Over
- * time the cache will grow to this size and may not shrink. Defaults to
- * 1000.
+ * Number of users that have failed authentication to keep in cache. Over time the cache will grow to this size and
+ * may not shrink. Defaults to 1000.
*/
protected int cacheSize = 1000;
/**
- * If a failed user is removed from the cache because the cache is too big
- * before it has been in the cache for at least this period of time (in
- * seconds) a warning message will be logged. Defaults to 3600 (1 hour).
+ * If a failed user is removed from the cache because the cache is too big before it has been in the cache for at
+ * least this period of time (in seconds) a warning message will be logged. Defaults to 3600 (1 hour).
*/
protected int cacheRemovalWarningTime = 3600;
/**
- * Users whose last authentication attempt failed. Entries will be ordered
- * in access order from least recent to most recent.
+ * Users whose last authentication attempt failed. Entries will be ordered in access order from least recent to most
+ * recent.
*/
- protected Map<String,LockRecord> failedUsers = null;
+ protected Map<String, LockRecord> failedUsers = null;
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected synchronized void startInternal() throws LifecycleException {
// Configure the list of failed users to delete the oldest entry once it
// exceeds the specified size
- failedUsers = new LinkedHashMap<>(cacheSize, 0.75f,
- true) {
+ failedUsers = new LinkedHashMap<>(cacheSize, 0.75f, true) {
private static final long serialVersionUID = 1L;
+
@Override
- protected boolean removeEldestEntry(
- Map.Entry<String, LockRecord> eldest) {
+ protected boolean removeEldestEntry(Map.Entry<String, LockRecord> eldest) {
if (size() > cacheSize) {
// Check to see if this element has been removed too quickly
- long timeInCache = (System.currentTimeMillis() -
- eldest.getValue().getLastFailureTime())/1000;
+ long timeInCache = (System.currentTimeMillis() - eldest.getValue().getLastFailureTime()) / 1000;
if (timeInCache < cacheRemovalWarningTime) {
- log.warn(sm.getString("lockOutRealm.removeWarning",
- eldest.getKey(), Long.valueOf(timeInCache)));
+ log.warn(
+ sm.getString("lockOutRealm.removeWarning", eldest.getKey(), Long.valueOf(timeInCache)));
}
return true;
}
@@ -117,36 +107,31 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Return the Principal associated with the specified username, which
- * matches the digest calculated using the given parameters using the
- * method described in RFC 2069; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username, which matches the digest calculated using the given
+ * parameters using the method described in RFC 2069; otherwise return <code>null</code>.
*
- * @param username Username of the Principal to look up
+ * @param username Username of the Principal to look up
* @param clientDigest Digest which has been submitted by the client
- * @param nonce Unique (or supposedly unique) token which has been used
- * for this request
- * @param realmName Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest :
- * MD5(Method + ":" + uri)
+ * @param nonce Unique (or supposedly unique) token which has been used for this request
+ * @param realmName Realm name
+ * @param md5a2 Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
*/
@Override
- public Principal authenticate(String username, String clientDigest,
- String nonce, String nc, String cnonce, String qop,
- String realmName, String md5a2) {
+ public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+ String qop, String realmName, String md5a2) {
- Principal authenticatedUser = super.authenticate(username, clientDigest, nonce, nc, cnonce,
- qop, realmName, md5a2);
+ Principal authenticatedUser = super.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realmName,
+ md5a2);
return filterLockedAccounts(username, authenticatedUser);
}
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>.
*
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*/
@Override
public Principal authenticate(String username, String credentials) {
@@ -156,16 +141,16 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Return the Principal associated with the specified chain of X509
- * client certificates. If there is none, return <code>null</code>.
+ * Return the Principal associated with the specified chain of X509 client certificates. If there is none, return
+ * <code>null</code>.
*
- * @param certs Array of client certificates, with the first one in
- * the array being the certificate of the client itself.
+ * @param certs Array of client certificates, with the first one in the array being the certificate of the client
+ * itself.
*/
@Override
public Principal authenticate(X509Certificate[] certs) {
String username = null;
- if (certs != null && certs.length >0) {
+ if (certs != null && certs.length > 0) {
username = certs[0].getSubjectX500Principal().toString();
}
@@ -214,8 +199,8 @@ public class LockOutRealm extends CombinedRealm {
/*
- * Filters authenticated principals to ensure that <code>null</code> is
- * returned for any user that is currently locked out.
+ * Filters authenticated principals to ensure that <code>null</code> is returned for any user that is currently
+ * locked out.
*/
private Principal filterLockedAccounts(String username, Principal authenticatedUser) {
// Register all failed authentications
@@ -238,8 +223,7 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Unlock the specified username. This will remove all records of
- * authentication failures for this user.
+ * Unlock the specified username. This will remove all records of authentication failures for this user.
*
* @param username The user to unlock
*/
@@ -249,9 +233,8 @@ public class LockOutRealm extends CombinedRealm {
}
/*
- * Checks to see if the current user is locked. If this is associated with
- * a login attempt, then the last access time will be recorded and any
- * attempt to authenticated a locked user will log a warning.
+ * Checks to see if the current user is locked. If this is associated with a login attempt, then the last access
+ * time will be recorded and any attempt to authenticated a locked user will log a warning.
*/
public boolean isLocked(String username) {
LockRecord lockRecord = null;
@@ -266,8 +249,7 @@ public class LockOutRealm extends CombinedRealm {
// Check to see if user is locked
if (lockRecord.getFailures() >= failureCount &&
- (System.currentTimeMillis() -
- lockRecord.getLastFailureTime())/1000 < lockOutTime) {
+ (System.currentTimeMillis() - lockRecord.getLastFailureTime()) / 1000 < lockOutTime) {
return true;
}
@@ -277,8 +259,7 @@ public class LockOutRealm extends CombinedRealm {
/*
- * After successful authentication, any record of previous authentication
- * failure is removed.
+ * After successful authentication, any record of previous authentication failure is removed.
*/
private synchronized void registerAuthSuccess(String username) {
// Successful authentication means removal from the list of failed users
@@ -287,8 +268,7 @@ public class LockOutRealm extends CombinedRealm {
/*
- * After a failed authentication, add the record of the failed
- * authentication.
+ * After a failed authentication, add the record of the failed authentication.
*/
private void registerAuthFailure(String username) {
LockRecord lockRecord = null;
@@ -299,9 +279,7 @@ public class LockOutRealm extends CombinedRealm {
} else {
lockRecord = failedUsers.get(username);
if (lockRecord.getFailures() >= failureCount &&
- ((System.currentTimeMillis() -
- lockRecord.getLastFailureTime())/1000)
- > lockOutTime) {
+ ((System.currentTimeMillis() - lockRecord.getLastFailureTime()) / 1000) > lockOutTime) {
// User was previously locked out but lockout has now
// expired so reset failure count
lockRecord.setFailures(0);
@@ -313,8 +291,8 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Get the number of failed authentication attempts required to lock the
- * user account.
+ * Get the number of failed authentication attempts required to lock the user account.
+ *
* @return the failureCount
*/
public int getFailureCount() {
@@ -323,8 +301,8 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Set the number of failed authentication attempts required to lock the
- * user account.
+ * Set the number of failed authentication attempts required to lock the user account.
+ *
* @param failureCount the failureCount to set
*/
public void setFailureCount(int failureCount) {
@@ -334,6 +312,7 @@ public class LockOutRealm extends CombinedRealm {
/**
* Get the period for which an account will be locked.
+ *
* @return the lockOutTime
*/
public int getLockOutTime() {
@@ -343,6 +322,7 @@ public class LockOutRealm extends CombinedRealm {
/**
* Set the period for which an account will be locked.
+ *
* @param lockOutTime the lockOutTime to set
*/
public void setLockOutTime(int lockOutTime) {
@@ -351,8 +331,8 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Get the maximum number of users for which authentication failure will be
- * kept in the cache.
+ * Get the maximum number of users for which authentication failure will be kept in the cache.
+ *
* @return the cacheSize
*/
public int getCacheSize() {
@@ -361,8 +341,8 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Set the maximum number of users for which authentication failure will be
- * kept in the cache.
+ * Set the maximum number of users for which authentication failure will be kept in the cache.
+ *
* @param cacheSize the cacheSize to set
*/
public void setCacheSize(int cacheSize) {
@@ -371,9 +351,9 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Get the minimum period a failed authentication must remain in the cache
- * to avoid generating a warning if it is removed from the cache to make
- * space for a new entry.
+ * Get the minimum period a failed authentication must remain in the cache to avoid generating a warning if it is
+ * removed from the cache to make space for a new entry.
+ *
* @return the cacheRemovalWarningTime
*/
public int getCacheRemovalWarningTime() {
@@ -382,9 +362,9 @@ public class LockOutRealm extends CombinedRealm {
/**
- * Set the minimum period a failed authentication must remain in the cache
- * to avoid generating a warning if it is removed from the cache to make
- * space for a new entry.
+ * Set the minimum period a failed authentication must remain in the cache to avoid generating a warning if it is
+ * removed from the cache to make space for a new entry.
+ *
* @param cacheRemovalWarningTime the cacheRemovalWarningTime to set
*/
public void setCacheRemovalWarningTime(int cacheRemovalWarningTime) {
diff --git a/java/org/apache/catalina/realm/MemoryRealm.java b/java/org/apache/catalina/realm/MemoryRealm.java
index 2584438291..4e90ee3a53 100644
--- a/java/org/apache/catalina/realm/MemoryRealm.java
+++ b/java/org/apache/catalina/realm/MemoryRealm.java
@@ -32,18 +32,16 @@ import org.apache.tomcat.util.file.ConfigFileLoader;
/**
- * Simple implementation of <b>Realm</b> that reads an XML file to configure
- * the valid users, passwords, and roles. The file format (and default file
- * location) are identical to those currently supported by Tomcat 3.X.
+ * Simple implementation of <b>Realm</b> that reads an XML file to configure the valid users, passwords, and roles. The
+ * file format (and default file location) are identical to those currently supported by Tomcat 3.X.
* <p>
- * <strong>IMPLEMENTATION NOTE</strong>: It is assumed that the in-memory
- * collection representing our defined users (and their roles) is initialized
- * at application startup and never modified again. Therefore, no thread
- * synchronization is performed around accesses to the principals collection.
+ * <strong>IMPLEMENTATION NOTE</strong>: It is assumed that the in-memory collection representing our defined users (and
+ * their roles) is initialized at application startup and never modified again. Therefore, no thread synchronization is
+ * performed around accesses to the principals collection.
*
* @author Craig R. McClanahan
*/
-public class MemoryRealm extends RealmBase {
+public class MemoryRealm extends RealmBase {
private static final Log log = LogFactory.getLog(MemoryRealm.class);
@@ -58,8 +56,8 @@ public class MemoryRealm extends RealmBase {
/**
- * The pathname (absolute or relative to Catalina's current working
- * directory) of the XML file containing our database information.
+ * The pathname (absolute or relative to Catalina's current working directory) of the XML file containing our
+ * database information.
*/
private String pathname = "conf/tomcat-users.xml";
@@ -67,7 +65,7 @@ public class MemoryRealm extends RealmBase {
/**
* The set of valid Principals for this Realm, keyed by user name.
*/
- private final Map<String,GenericPrincipal> principals = new HashMap<>();
+ private final Map<String, GenericPrincipal> principals = new HashMap<>();
/**
@@ -89,8 +87,8 @@ public class MemoryRealm extends RealmBase {
/**
- * Set the pathname of our XML file containing user definitions. If a
- * relative pathname is specified, it is resolved against "catalina.base".
+ * Set the pathname of our XML file containing user definitions. If a relative pathname is specified, it is resolved
+ * against "catalina.base".
*
* @param pathname The new pathname
*/
@@ -105,12 +103,12 @@ public class MemoryRealm extends RealmBase {
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>.
+ *
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
@@ -166,7 +164,7 @@ public class MemoryRealm extends RealmBase {
*
* @param username User's username
* @param password User's password (clear text)
- * @param roles Comma-delimited set of roles associated with this user
+ * @param roles Comma-delimited set of roles associated with this user
*/
void addUser(String username, String password, String roles) {
@@ -195,8 +193,8 @@ public class MemoryRealm extends RealmBase {
/**
- * @return a configured <code>Digester</code> to use for processing
- * the XML input file, creating a new one if necessary.
+ * @return a configured <code>Digester</code> to use for processing the XML input file, creating a new one if
+ * necessary.
*/
protected Digester getDigester() {
synchronized (digesterLock) {
@@ -238,12 +236,11 @@ public class MemoryRealm extends RealmBase {
// ------------------------------------------------------ Lifecycle Methods
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected void startInternal() throws LifecycleException {
diff --git a/java/org/apache/catalina/realm/MemoryRuleSet.java b/java/org/apache/catalina/realm/MemoryRuleSet.java
index 9a114e9787..b8d1227884 100644
--- a/java/org/apache/catalina/realm/MemoryRuleSet.java
+++ b/java/org/apache/catalina/realm/MemoryRuleSet.java
@@ -22,8 +22,9 @@ import org.apache.tomcat.util.digester.RuleSet;
import org.xml.sax.Attributes;
/**
- * <p><strong>RuleSet</strong> for recognizing the users defined in the
- * XML file processed by <code>MemoryRealm</code>.</p>
+ * <p>
+ * <strong>RuleSet</strong> for recognizing the users defined in the XML file processed by <code>MemoryRealm</code>.
+ * </p>
*
* @author Craig R. McClanahan
*/
@@ -41,8 +42,7 @@ public class MemoryRuleSet implements RuleSet {
// ------------------------------------------------------------ Constructor
/**
- * Construct an instance of this <code>RuleSet</code> with the default
- * matching pattern prefix.
+ * Construct an instance of this <code>RuleSet</code> with the default matching pattern prefix.
*/
public MemoryRuleSet() {
this("tomcat-users/");
@@ -50,11 +50,9 @@ public class MemoryRuleSet implements RuleSet {
/**
- * Construct an instance of this <code>RuleSet</code> with the specified
- * matching pattern prefix.
+ * Construct an instance of this <code>RuleSet</code> with the specified matching pattern prefix.
*
- * @param prefix Prefix for matching pattern rules (including the
- * trailing slash character)
+ * @param prefix Prefix for matching pattern rules (including the trailing slash character)
*/
public MemoryRuleSet(String prefix) {
this.prefix = prefix;
@@ -65,13 +63,12 @@ public class MemoryRuleSet implements RuleSet {
/**
- * <p>Add the set of Rule instances defined in this RuleSet to the
- * specified <code>Digester</code> instance, associating them with
- * our namespace URI (if any). This method should only be called
- * by a Digester instance.</p>
+ * <p>
+ * Add the set of Rule instances defined in this RuleSet to the specified <code>Digester</code> instance,
+ * associating them with our namespace URI (if any). This method should only be called by a Digester instance.
+ * </p>
*
- * @param digester Digester instance to which the new Rule instances
- * should be added.
+ * @param digester Digester instance to which the new Rule instances should be added.
*/
@Override
public void addRuleInstances(Digester digester) {
@@ -104,8 +101,7 @@ final class MemoryUserRule extends Rule {
* @param attributes The attribute list for this element
*/
@Override
- public void begin(String namespace, String name, Attributes attributes)
- throws Exception {
+ public void begin(String namespace, String name, Attributes attributes) throws Exception {
String username = attributes.getValue("username");
if (username == null) {
@@ -114,8 +110,7 @@ final class MemoryUserRule extends Rule {
String password = attributes.getValue("password");
String roles = attributes.getValue("roles");
- MemoryRealm realm =
- (MemoryRealm) digester.peek(digester.getCount() - 1);
+ MemoryRealm realm = (MemoryRealm) digester.peek(digester.getCount() - 1);
realm.addUser(username, password, roles);
}
diff --git a/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java b/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java
index d43465c801..7945af8490 100644
--- a/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java
+++ b/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java
@@ -32,22 +32,21 @@ import org.apache.tomcat.util.security.ConcurrentMessageDigest;
/**
* This credential handler supports the following forms of stored passwords:
* <ul>
- * <li><b>encodedCredential</b> - a hex encoded digest of the password digested
- * using the configured digest</li>
- * <li><b>{MD5}encodedCredential</b> - a Base64 encoded MD5 digest of the
- * password</li>
- * <li><b>{SHA}encodedCredential</b> - a Base64 encoded SHA1 digest of the
- * password</li>
- * <li><b>{SSHA}encodedCredential</b> - 20 byte Base64 encoded SHA1 digest
- * followed by variable length salt.
- * <pre>{SSHA}<sha-1 digest:20><salt:n></pre></li>
- * <li><b>salt$iterationCount$encodedCredential</b> - a hex encoded salt,
- * iteration code and a hex encoded credential, each separated by $</li>
- * </ul>
+ * <li><b>encodedCredential</b> - a hex encoded digest of the password digested using the configured digest</li>
+ * <li><b>{MD5}encodedCredential</b> - a Base64 encoded MD5 digest of the password</li>
+ * <li><b>{SHA}encodedCredential</b> - a Base64 encoded SHA1 digest of the password</li>
+ * <li><b>{SSHA}encodedCredential</b> - 20 byte Base64 encoded SHA1 digest followed by variable length salt.
+ *
+ * <pre>
+ * {SSHA}<sha-1 digest:20><salt:n>
+ * </pre>
*
+ * </li>
+ * <li><b>salt$iterationCount$encodedCredential</b> - a hex encoded salt, iteration code and a hex encoded credential,
+ * each separated by $</li>
+ * </ul>
* <p>
- * If the stored password form does not include an iteration count then an
- * iteration count of 1 is used.
+ * If the stored password form does not include an iteration count then an iteration count of 1 is used.
* <p>
* If the stored password form does not include salt then no salt is used.
*/
@@ -109,8 +108,8 @@ public class MessageDigestCredentialHandler extends DigestCredentialHandlerBase
// Server is storing digested passwords with a prefix indicating
// the digest type
String base64ServerDigest = storedCredentials.substring(5);
- byte[] userDigest = ConcurrentMessageDigest.digest(
- getAlgorithm(), inputCredentials.getBytes(StandardCharsets.ISO_8859_1));
+ byte[] userDigest = ConcurrentMessageDigest.digest(getAlgorithm(),
+ inputCredentials.getBytes(StandardCharsets.ISO_8859_1));
String base64UserDigest = Base64.encodeBase64String(userDigest);
return DigestCredentialHandlerBase.equals(base64UserDigest, base64ServerDigest, false);
@@ -134,8 +133,7 @@ public class MessageDigestCredentialHandler extends DigestCredentialHandlerBase
// Generate the digested form of the user provided password
// using the salt
byte[] userDigestBytes = ConcurrentMessageDigest.digest(getAlgorithm(),
- inputCredentials.getBytes(StandardCharsets.ISO_8859_1),
- serverSaltBytes);
+ inputCredentials.getBytes(StandardCharsets.ISO_8859_1), serverSaltBytes);
return Arrays.equals(userDigestBytes, serverDigestBytes);
} else if (storedCredentials.indexOf('$') > -1) {
diff --git a/java/org/apache/catalina/realm/NestedCredentialHandler.java b/java/org/apache/catalina/realm/NestedCredentialHandler.java
index 91390f255f..286c3e03a4 100644
--- a/java/org/apache/catalina/realm/NestedCredentialHandler.java
+++ b/java/org/apache/catalina/realm/NestedCredentialHandler.java
@@ -38,11 +38,8 @@ public class NestedCredentialHandler implements CredentialHandler {
/**
- * The input credentials will be passed to the first nested
- * {@link CredentialHandler}. If no nested {@link CredentialHandler} are
- * configured then <code>null</code> will be returned.
- *
- * {@inheritDoc}
+ * The input credentials will be passed to the first nested {@link CredentialHandler}. If no nested
+ * {@link CredentialHandler} are configured then <code>null</code> will be returned. {@inheritDoc}
*/
@Override
public String mutate(String inputCredentials) {
diff --git a/java/org/apache/catalina/realm/NullRealm.java b/java/org/apache/catalina/realm/NullRealm.java
index e801b5e6d7..83e4693d9c 100644
--- a/java/org/apache/catalina/realm/NullRealm.java
+++ b/java/org/apache/catalina/realm/NullRealm.java
@@ -19,9 +19,8 @@ package org.apache.catalina.realm;
import java.security.Principal;
/**
- * Minimal Realm implementation that always returns null when an attempt is made
- * to validate a user name and password. It is intended to be used as a default
- * Realm implementation when no other Realm is specified.
+ * Minimal Realm implementation that always returns null when an attempt is made to validate a user name and password.
+ * It is intended to be used as a default Realm implementation when no other Realm is specified.
*/
public class NullRealm extends RealmBase {
diff --git a/java/org/apache/catalina/realm/RealmBase.java b/java/org/apache/catalina/realm/RealmBase.java
index 0bac871696..25149713ef 100644
--- a/java/org/apache/catalina/realm/RealmBase.java
+++ b/java/org/apache/catalina/realm/RealmBase.java
@@ -63,9 +63,8 @@ import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSName;
/**
- * Simple implementation of <b>Realm</b> that reads an XML file to configure
- * the valid users, passwords, and roles. The file format (and default file
- * location) are identical to those currently supported by Tomcat 3.X.
+ * Simple implementation of <b>Realm</b> that reads an XML file to configure the valid users, passwords, and roles. The
+ * file format (and default file location) are identical to those currently supported by Tomcat 3.X.
*
* @author Craig R. McClanahan
*/
@@ -73,8 +72,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
private static final Log log = LogFactory.getLog(RealmBase.class);
- private static final List<Class<? extends DigestCredentialHandlerBase>> credentialHandlerClasses =
- new ArrayList<>();
+ private static final List<Class<? extends DigestCredentialHandlerBase>> credentialHandlerClasses = new ArrayList<>();
static {
// Order is important since it determines the search order for a
@@ -120,8 +118,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
protected boolean validate = true;
/**
- * The name of the class to use for retrieving user names from X509
- * certificates.
+ * The name of the class to use for retrieving user names from X509 certificates.
*/
protected String x509UsernameRetrieverClassName;
@@ -137,8 +134,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * When processing users authenticated via the GSS-API, should any
- * "@..." be stripped from the end of the user name?
+ * When processing users authenticated via the GSS-API, should any "@..." be stripped from the end of the
+ * user name?
*/
protected boolean stripRealmForGss = true;
@@ -149,9 +146,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
// ------------------------------------------------------------- Properties
/**
- * @return The HTTP status code used when the container needs to issue an
- * HTTP redirect to meet the requirements of a configured transport
- * guarantee.
+ * @return The HTTP status code used when the container needs to issue an HTTP redirect to meet the requirements of
+ * a configured transport guarantee.
*/
public int getTransportGuaranteeRedirectStatus() {
return transportGuaranteeRedirectStatus;
@@ -159,11 +155,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Set the HTTP status code used when the container needs to issue an HTTP
- * redirect to meet the requirements of a configured transport guarantee.
+ * Set the HTTP status code used when the container needs to issue an HTTP redirect to meet the requirements of a
+ * configured transport guarantee.
*
- * @param transportGuaranteeRedirectStatus The status to use. This value is
- * not validated
+ * @param transportGuaranteeRedirectStatus The status to use. This value is not validated
*/
public void setTransportGuaranteeRedirectStatus(int transportGuaranteeRedirectStatus) {
this.transportGuaranteeRedirectStatus = transportGuaranteeRedirectStatus;
@@ -207,6 +202,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Return the all roles mode.
+ *
* @return A string representation of the current all roles mode
*/
public String getAllRolesMode() {
@@ -216,6 +212,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Set the all roles mode.
+ *
* @param allRolesMode A string representation of the new all roles mode
*/
public void setAllRolesMode(String allRolesMode) {
@@ -225,6 +222,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Return the "validate certificate chains" flag.
+ *
* @return The value of the validate certificate chains flag
*/
public boolean getValidate() {
@@ -244,22 +242,20 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
/**
- * Gets the name of the class that will be used to extract user names
- * from X509 client certificates.
- * @return The name of the class that will be used to extract user names
- * from X509 client certificates.
+ * Gets the name of the class that will be used to extract user names from X509 client certificates.
+ *
+ * @return The name of the class that will be used to extract user names from X509 client certificates.
*/
public String getX509UsernameRetrieverClassName() {
return x509UsernameRetrieverClassName;
}
/**
- * Sets the name of the class that will be used to extract user names
- * from X509 client certificates. The class must implement
- * X509UsernameRetriever.
+ * Sets the name of the class that will be used to extract user names from X509 client certificates. The class must
+ * implement X509UsernameRetriever.
+ *
+ * @param className The name of the class that will be used to extract user names from X509 client certificates.
*
- * @param className The name of the class that will be used to extract user names
- * from X509 client certificates.
* @see X509UsernameRetriever
*/
public void setX509UsernameRetrieverClassName(String className) {
@@ -293,8 +289,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Return the Principal associated with the specified username, if there
- * is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username, if there is one; otherwise return <code>null</code>.
*
* @param username Username of the Principal to look up
*/
@@ -314,22 +309,21 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Return the Principal associated with the specified username and
- * credentials, if there is one; otherwise return <code>null</code>.
+ * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+ * <code>null</code>.
+ *
+ * @param username Username of the Principal to look up
+ * @param credentials Password or other credentials to use in authenticating this username
*
- * @param username Username of the Principal to look up
- * @param credentials Password or other credentials to use in
- * authenticating this username
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
public Principal authenticate(String username, String credentials) {
// No user or no credentials
// Can't possibly authenticate, don't bother doing anything.
- if(username == null || credentials == null) {
+ if (username == null || credentials == null) {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("realmBase.authenticateFailure",
- username));
+ containerLog.trace(sm.getString("realmBase.authenticateFailure", username));
}
return null;
}
@@ -343,8 +337,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
getCredentialHandler().mutate(credentials);
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("realmBase.authenticateFailure",
- username));
+ containerLog.trace(sm.getString("realmBase.authenticateFailure", username));
}
return null;
}
@@ -353,14 +346,12 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
if (validated) {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("realmBase.authenticateSuccess",
- username));
+ containerLog.trace(sm.getString("realmBase.authenticateSuccess", username));
}
return getPrincipal(username);
} else {
if (containerLog.isTraceEnabled()) {
- containerLog.trace(sm.getString("realmBase.authenticateFailure",
- username));
+ containerLog.trace(sm.getString("realmBase.authenticateFailure", username));
}
return null;
}
@@ -368,28 +359,24 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Try to authenticate with the specified username, which
- * matches the digest calculated using the given parameters using the
- * method described in RFC 2617 (which is a superset of RFC 2069).
+ * Try to authenticate with the specified username, which matches the digest calculated using the given parameters
+ * using the method described in RFC 2617 (which is a superset of RFC 2069).
*
- * @param username Username of the Principal to look up
+ * @param username Username of the Principal to look up
* @param clientDigest Digest which has been submitted by the client
- * @param nonce Unique (or supposedly unique) token which has been used
- * for this request
- * @param nc the nonce counter
- * @param cnonce the client chosen nonce
- * @param qop the "quality of protection" (<code>nc</code> and <code>cnonce</code>
- * will only be used, if <code>qop</code> is not <code>null</code>).
- * @param realm Realm name
- * @param md5a2 Second MD5 digest used to calculate the digest :
- * MD5(Method + ":" + uri)
+ * @param nonce Unique (or supposedly unique) token which has been used for this request
+ * @param nc the nonce counter
+ * @param cnonce the client chosen nonce
+ * @param qop the "quality of protection" (<code>nc</code> and <code>cnonce</code> will only be used, if
+ * <code>qop</code> is not <code>null</code>).
+ * @param realm Realm name
+ * @param md5a2 Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
+ *
* @return the associated principal, or <code>null</code> if there is none.
*/
@Override
- public Principal authenticate(String username, String clientDigest,
- String nonce, String nc, String cnonce,
- String qop, String realm,
- String md5a2) {
+ public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+ String qop, String realm, String md5a2) {
// In digest auth, digests are always lower case
String md5a1 = getDigest(username, realm);
@@ -401,25 +388,23 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
if (qop == null) {
serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2;
} else {
- serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" +
- cnonce + ":" + qop + ":" + md5a2;
+ serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2;
}
byte[] valueBytes = null;
try {
valueBytes = serverDigestValue.getBytes(getDigestCharset());
} catch (UnsupportedEncodingException uee) {
- throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()), uee);
+ throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()),
+ uee);
}
String serverDigest = MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
if (log.isDebugEnabled()) {
- log.debug("Digest : " + clientDigest + " Username:" + username
- + " ClientDigest:" + clientDigest + " nonce:" + nonce
- + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop
- + " realm:" + realm + "md5a2:" + md5a2
- + " Server digest:" + serverDigest);
+ log.debug("Digest : " + clientDigest + " Username:" + username + " ClientDigest:" + clientDigest +
+ " nonce:" + nonce + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop + " realm:" + realm +
+ "md5a2:" + md5a2 + " Server digest:" + serverDigest);
}
if (serverDigest.equals(clientDigest)) {
@@ -431,11 +416,11 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Return the Principal associated with the specified chain of X509
- * client certificates. If there is none, return <code>null</code>.
+ * Return the Principal associated with the specified chain of X509 client certificates. If there is none, return
+ * <code>null</code>.
*
- * @param certs Array of client certificates, with the first one in
- * the array being the certificate of the client itself.
+ * @param certs Array of client certificates, with the first one in the array being the certificate of the client
+ * itself.
*/
@Override
public Principal authenticate(X509Certificate certs[]) {
@@ -451,8 +436,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
if (validate) {
for (X509Certificate cert : certs) {
if (log.isDebugEnabled()) {
- log.debug(" Checking validity for '" +
- cert.getSubjectX500Principal().toString() + "'");
+ log.debug(" Checking validity for '" + cert.getSubjectX500Principal().toString() + "'");
}
try {
cert.checkValidity();
@@ -483,20 +467,18 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
log.warn(sm.getString("realmBase.gssNameFail"), e);
}
- if (gssName!= null) {
+ if (gssName != null) {
GSSCredential gssCredential = null;
if (storeCred) {
if (gssContext.getCredDelegState()) {
try {
gssCredential = gssContext.getDelegCred();
} catch (GSSException e) {
- log.warn(sm.getString(
- "realmBase.delegatedCredentialFail", gssName), e);
+ log.warn(sm.getString("realmBase.delegatedCredentialFail", gssName), e);
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "realmBase.credentialNotDelegated", gssName));
+ log.debug(sm.getString("realmBase.credentialNotDelegated", gssName));
}
}
}
@@ -526,9 +508,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Execute a periodic task, such as reloading, etc. This method will be
- * invoked inside the classloading context of this container. Unexpected
- * throwables will be caught and logged.
+ * Execute a periodic task, such as reloading, etc. This method will be invoked inside the classloading context of
+ * this container. Unexpected throwables will be caught and logged.
*/
@Override
public void backgroundProcess() {
@@ -537,15 +518,14 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Return the SecurityConstraints configured to guard the request URI for
- * this request, or <code>null</code> if there is no such constraint.
+ * Return the SecurityConstraints configured to guard the request URI for this request, or <code>null</code> if
+ * there is no such constraint.
*
* @param request Request we are processing
* @param context Context the Request is mapped to
*/
@Override
- public SecurityConstraint [] findSecurityConstraints(Request request,
- Context context) {
+ public SecurityConstraint[] findSecurityConstraints(Request request, Context context) {
ArrayList<SecurityConstraint> results = null;
// Are there any defined security constraints?
@@ -578,9 +558,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
if (log.isDebugEnabled()) {
- log.debug(" Checking constraint '" + constraints[i] +
- "' against " + method + " " + uri + " --> " +
- constraints[i].included(uri, method));
+ log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+ constraints[i].included(uri, method));
}
for (SecurityCollection securityCollection : collections) {
@@ -607,25 +586,24 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
- if(found) {
+ if (found) {
return resultsToArray(results);
}
int longest = -1;
for (i = 0; i < constraints.length; i++) {
- SecurityCollection [] collection = constraints[i].findCollections();
+ SecurityCollection[] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
- if ( collection == null) {
+ if (collection == null) {
continue;
}
if (log.isDebugEnabled()) {
- log.debug(" Checking constraint '" + constraints[i] +
- "' against " + method + " " + uri + " --> " +
- constraints[i].included(uri, method));
+ log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+ constraints[i].included(uri, method));
}
for (SecurityCollection securityCollection : collection) {
@@ -640,8 +618,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
boolean matched = false;
int length = -1;
for (String pattern : patterns) {
- if (pattern.startsWith("/") && pattern.endsWith("/*") &&
- pattern.length() >= longest) {
+ if (pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) {
if (pattern.length() == 2) {
matched = true;
@@ -673,45 +650,43 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
- if(found) {
- return resultsToArray(results);
+ if (found) {
+ return resultsToArray(results);
}
for (i = 0; i < constraints.length; i++) {
- SecurityCollection [] collection = constraints[i].findCollections();
+ SecurityCollection[] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
- if ( collection == null) {
+ if (collection == null) {
continue;
}
if (log.isDebugEnabled()) {
- log.debug(" Checking constraint '" + constraints[i] +
- "' against " + method + " " + uri + " --> " +
- constraints[i].included(uri, method));
+ log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+ constraints[i].included(uri, method));
}
boolean matched = false;
int pos = -1;
- for(int j=0; j < collection.length; j++){
- String [] patterns = collection[j].findPatterns();
+ for (int j = 0; j < collection.length; j++) {
+ String[] patterns = collection[j].findPatterns();
// If patterns is null, continue to avoid an NPE
// See Bugzilla 30624
- if ( patterns == null) {
+ if (patterns == null) {
continue;
}
- for(int k=0; k < patterns.length && !matched; k++) {
+ for (int k = 0; k < patterns.length && !matched; k++) {
String pattern = patterns[k];
- if(pattern.startsWith("*.")){
+ if (pattern.startsWith("*.")) {
int slash = uri.lastIndexOf('/');
int dot = uri.lastIndexOf('.');
- if(slash >= 0 && dot > slash &&
- dot != uri.length()-1 &&
- uri.length()-dot == pattern.length()-1) {
- if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) {
+ if (slash >= 0 && dot > slash && dot != uri.length() - 1 &&
+ uri.length() - dot == pattern.length() - 1) {
+ if (pattern.regionMatches(1, uri, dot, uri.length() - dot)) {
matched = true;
pos = j;
}
@@ -719,10 +694,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
}
- if(matched) {
+ if (matched) {
found = true;
- if(collection[pos].findMethod(method)) {
- if(results == null) {
+ if (collection[pos].findMethod(method)) {
+ if (results == null) {
results = new ArrayList<>();
}
results.add(constraints[i]);
@@ -730,23 +705,22 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
- if(found) {
+ if (found) {
return resultsToArray(results);
}
for (i = 0; i < constraints.length; i++) {
- SecurityCollection [] collection = constraints[i].findCollections();
+ SecurityCollection[] collection = constraints[i].findCollections();
// If collection is null, continue to avoid an NPE
// See Bugzilla 30624
- if ( collection == null) {
+ if (collection == null) {
continue;
}
if (log.isDebugEnabled()) {
- log.debug(" Checking constraint '" + constraints[i] +
- "' against " + method + " " + uri + " --> " +
- constraints[i].included(uri, method));
+ log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+ constraints[i].included(uri, method));
}
for (SecurityCollection securityCollection : collection) {
@@ -774,7 +748,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
- if(results == null) {
+ if (results == null) {
// No applicable security constraint was found
if (log.isDebugEnabled()) {
log.debug(" No applicable constraint located");
@@ -786,33 +760,28 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Convert an ArrayList to a SecurityConstraint [].
*/
- private SecurityConstraint [] resultsToArray(
- ArrayList<SecurityConstraint> results) {
- if(results == null || results.size() == 0) {
+ private SecurityConstraint[] resultsToArray(ArrayList<SecurityConstraint> results) {
+ if (results == null || results.size() == 0) {
return null;
}
- return results.toArray(new SecurityConstraint [0]);
+ return results.toArray(new SecurityConstraint[0]);
}
/**
- * Perform access control based on the specified authorization constraint.
- * Return <code>true</code> if this constraint is satisfied and processing
- * should continue, or <code>false</code> otherwise.
+ * Perform access control based on the specified authorization constraint. Return <code>true</code> if this
+ * constraint is satisfied and processing should continue, or <code>false</code> otherwise.
*
- * @param request Request we are processing
- * @param response Response we are creating
+ * @param request Request we are processing
+ * @param response Response we are creating
* @param constraints Security constraint we are enforcing
- * @param context The Context to which client of this class is attached.
+ * @param context The Context to which client of this class is attached.
*
* @exception IOException if an input/output error occurs
*/
@Override
- public boolean hasResourcePermission(Request request,
- Response response,
- SecurityConstraint []constraints,
- Context context)
- throws IOException {
+ public boolean hasResourcePermission(Request request, Response response, SecurityConstraint[] constraints,
+ Context context) throws IOException {
if (constraints == null || constraints.length == 0) {
return true;
@@ -844,9 +813,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
log.debug("Passing all authenticated users");
}
status = true;
- }
- else if (roles.length == 0 && !constraint.getAllRoles() &&
- !constraint.getAuthenticatedUsers()) {
+ } else if (roles.length == 0 && !constraint.getAllRoles() && !constraint.getAuthenticatedUsers()) {
if (constraint.getAuthConstraint()) {
if (log.isDebugEnabled()) {
log.debug("No roles");
@@ -878,8 +845,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
- if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE &&
- !status && principal != null) {
+ if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE && !status && principal != null) {
if (log.isDebugEnabled()) {
log.debug("Checking for all roles mode: " + allRolesMode);
}
@@ -910,10 +876,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
// Return a "Forbidden" message denying access to this resource
- if(!status) {
- response.sendError
- (HttpServletResponse.SC_FORBIDDEN,
- sm.getString("realmBase.forbidden"));
+ if (!status) {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden"));
}
return status;
@@ -921,11 +885,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * {@inheritDoc}
- *
- * This method or {@link #hasRoleInternal(Principal,
- * String)} can be overridden by Realm implementations, but the default is
- * adequate when an instance of <code>GenericPrincipal</code> is used to
+ * {@inheritDoc} This method or {@link #hasRoleInternal(Principal, String)} can be overridden by Realm
+ * implementations, but the default is adequate when an instance of <code>GenericPrincipal</code> is used to
* represent authenticated Principals from this Realm.
*/
@Override
@@ -959,20 +920,16 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Check if the specified Principal has the specified
- * security role, within the context of this Realm.
- *
- * This method or {@link #hasRoleInternal(Principal,
- * String)} can be overridden by Realm implementations, but the default is
- * adequate when an instance of <code>GenericPrincipal</code> is used to
- * represent authenticated Principals from this Realm.
+ * Check if the specified Principal has the specified security role, within the context of this Realm. This method
+ * or {@link #hasRoleInternal(Principal, String)} can be overridden by Realm implementations, but the default is
+ * adequate when an instance of <code>GenericPrincipal</code> is used to represent authenticated Principals from
+ * this Realm.
*
* @param principal Principal for whom the role is to be checked
- * @param role Security role to be checked
+ * @param role Security role to be checked
*
- * @return <code>true</code> if the specified Principal has the specified
- * security role, within the context of this Realm; otherwise return
- * <code>false</code>.
+ * @return <code>true</code> if the specified Principal has the specified security role, within the context of this
+ * Realm; otherwise return <code>false</code>.
*/
protected boolean hasRoleInternal(Principal principal, String role) {
// Should be overridden in JAASRealm - to avoid pretty inefficient conversions
@@ -986,22 +943,19 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Enforce any user data constraint required by the security constraint
- * guarding this request URI. Return <code>true</code> if this constraint
- * was not violated and processing should continue, or <code>false</code>
- * if we have created a response already.
+ * Enforce any user data constraint required by the security constraint guarding this request URI. Return
+ * <code>true</code> if this constraint was not violated and processing should continue, or <code>false</code> if we
+ * have created a response already.
*
- * @param request Request we are processing
- * @param response Response we are creating
+ * @param request Request we are processing
+ * @param response Response we are creating
* @param constraints Security constraint being checked
*
* @exception IOException if an input/output error occurs
*/
@Override
- public boolean hasUserDataPermission(Request request,
- Response response,
- SecurityConstraint []constraints)
- throws IOException {
+ public boolean hasUserDataPermission(Request request, Response response, SecurityConstraint[] constraints)
+ throws IOException {
// Is there a relevant user data constraint?
if (constraints == null || constraints.length == 0) {
@@ -1041,9 +995,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
if (log.isDebugEnabled()) {
log.debug(" SSL redirect is disabled");
}
- response.sendError
- (HttpServletResponse.SC_FORBIDDEN,
- request.getRequestURI());
+ response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
return false;
}
@@ -1054,17 +1006,15 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
// Protocol
file.append(protocol).append("://").append(host);
// Host with port
- if(redirectPort != 443) {
+ if (redirectPort != 443) {
file.append(':').append(redirectPort);
}
// URI
file.append(request.getRequestURI());
String requestedSessionId = request.getRequestedSessionId();
- if ((requestedSessionId != null) &&
- request.isRequestedSessionIdFromURL()) {
+ if ((requestedSessionId != null) && request.isRequestedSessionIdFromURL()) {
file.append(';');
- file.append(SessionConfig.getSessionUriParamName(
- request.getContext()));
+ file.append(SessionConfig.getSessionUriParamName(request.getContext()));
file.append('=');
file.append(requestedSessionId);
}
@@ -1109,12 +1059,11 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
/**
- * Prepare for the beginning of active use of the public methods of this
- * component and implement the requirements of
+ * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that prevents this component from being used
+ * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+ * used
*/
@Override
protected void startInternal() throws LifecycleException {
@@ -1127,12 +1076,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Gracefully terminate the active use of the public methods of this
- * component and implement the requirements of
+ * Gracefully terminate the active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
+ * @exception LifecycleException if this component detects a fatal error that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
@@ -1162,8 +1109,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Return the digest associated with given principal's user name.
- * @param username the user name
+ *
+ * @param username the user name
* @param realmName the realm name
+ *
* @return the digest for the specified user
*/
protected String getDigest(String username, String realmName) {
@@ -1172,14 +1121,14 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
return getPassword(username);
}
- String digestValue = username + ":" + realmName + ":"
- + getPassword(username);
+ String digestValue = username + ":" + realmName + ":" + getPassword(username);
byte[] valueBytes = null;
try {
valueBytes = digestValue.getBytes(getDigestCharset());
} catch (UnsupportedEncodingException uee) {
- throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()), uee);
+ throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()),
+ uee);
}
return MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
@@ -1207,7 +1156,9 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Get the password for the specified user.
+ *
* @param username The user name
+ *
* @return the password associated with the given principal's user name.
*/
protected abstract String getPassword(String username);
@@ -1215,13 +1166,15 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Get the principal associated with the specified certificate.
+ *
* @param usercert The user certificate
+ *
* @return the Principal associated with the given certificate.
*/
protected Principal getPrincipal(X509Certificate usercert) {
String username = x509UsernameRetriever.getUsername(usercert);
- if(log.isDebugEnabled()) {
+ if (log.isDebugEnabled()) {
log.debug(sm.getString("realmBase.gotX509Username", username));
}
@@ -1231,7 +1184,9 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Get the principal associated with the specified user.
+ *
* @param username The user name
+ *
* @return the Principal associated with the given user name.
*/
protected abstract Principal getPrincipal(String username);
@@ -1240,12 +1195,12 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
* Get the principal associated with the specified {@link GSSName}.
*
- * @param gssName The GSS name
+ * @param gssName The GSS name
* @param gssCredential the GSS credential of the principal
+ *
* @return the principal associated with the given user name.
*/
- protected Principal getPrincipal(GSSName gssName,
- GSSCredential gssCredential) {
+ protected Principal getPrincipal(GSSName gssName, GSSCredential gssCredential) {
String name = gssName.toString();
if (isStripRealmForGss()) {
@@ -1267,10 +1222,9 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
/**
- * Return the Server object that is the ultimate parent for the container
- * with which this Realm is associated. If the server cannot be found (eg
- * because the container hierarchy is not complete), <code>null</code> is
- * returned.
+ * Return the Server object that is the ultimate parent for the container with which this Realm is associated. If
+ * the server cannot be found (eg because the container hierarchy is not complete), <code>null</code> is returned.
+ *
* @return the Server associated with the realm
*/
protected Server getServer() {
@@ -1282,7 +1236,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
c = c.getParent();
}
if (c instanceof Engine) {
- Service s = ((Engine)c).getService();
+ Service s = ((Engine) c).getService();
if (s != null) {
return s.getServer();
}
@@ -1294,38 +1248,33 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
// --------------------------------------------------------- Static Methods
/**
- * Generate a stored credential string for the given password and associated
- * parameters.
- * <p>The following parameters are supported:</p>
+ * Generate a stored credential string for the given password and associated parameters.
+ * <p>
+ * The following parameters are supported:
+ * </p>
* <ul>
- * <li><b>-a</b> - The algorithm to use to generate the stored
- * credential. If not specified a default of SHA-512 will be
- * used.</li>
- * <li><b>-e</b> - The encoding to use for any byte to/from character
- * conversion that may be necessary. If not specified, the
- * system encoding ({@link Charset#defaultCharset()}) will
- * be used.</li>
- * <li><b>-i</b> - The number of iterations to use when generating the
- * stored credential. If not specified, the default for the
- * CredentialHandler will be used.</li>
- * <li><b>-s</b> - The length (in bytes) of salt to generate and store as
- * part of the credential. If not specified, the default for
- * the CredentialHandler will be used.</li>
- * <li><b>-k</b> - The length (in bits) of the key(s), if any, created while
- * generating the credential. If not specified, the default
- * for the CredentialHandler will be used.</li>
- * <li><b>-h</b> - The fully qualified class name of the CredentialHandler
- * to use. If not specified, the built-in handlers will be
- * tested in turn and the first one to accept the specified
- * algorithm will be used.</li>
+ * <li><b>-a</b> - The algorithm to use to generate the stored credential. If not specified a default of SHA-512
+ * will be used.</li>
+ * <li><b>-e</b> - The encoding to use for any byte to/from character conversion that may be necessary. If not
+ * specified, the system encoding ({@link Charset#defaultCharset()}) will be used.</li>
+ * <li><b>-i</b> - The number of iterations to use when generating the stored credential. If not specified, the
+ * default for the CredentialHandler will be used.</li>
+ * <li><b>-s</b> - The length (in bytes) of salt to generate and store as part of the credential. If not specified,
+ * the default for the CredentialHandler will be used.</li>
+ * <li><b>-k</b> - The length (in bits) of the key(s), if any, created while generating the credential. If not
+ * specified, the default for the CredentialHandler will be used.</li>
+ * <li><b>-h</b> - The fully qualified class name of the CredentialHandler to use. If not specified, the built-in
+ * handlers will be tested in turn and the first one to accept the specified algorithm will be used.</li>
* </ul>
- * <p>This generation process currently supports the following
- * CredentialHandlers, the correct one being selected based on the algorithm
- * specified:</p>
+ * <p>
+ * This generation process currently supports the following CredentialHandlers, the correct one being selected based
+ * on the algorithm specified:
+ * </p>
* <ul>
* <li>{@link MessageDigestCredentialHandler}</li>
* <li>{@link SecretKeyCredentialHandler}</li>
* </ul>
+ *
* @param args The parameters passed on the command line
*/
public static void main(String args[]) {
@@ -1348,37 +1297,36 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
int argIndex = 0;
- while (args.length > argIndex + 2 && args[argIndex].length() == 2 &&
- args[argIndex].charAt(0) == '-' ) {
+ while (args.length > argIndex + 2 && args[argIndex].length() == 2 && args[argIndex].charAt(0) == '-') {
switch (args[argIndex].charAt(1)) {
- case 'a': {
- algorithm = args[argIndex + 1];
- break;
- }
- case 'e': {
- encoding = args[argIndex + 1];
- break;
- }
- case 'i': {
- iterations = Integer.parseInt(args[argIndex + 1]);
- break;
- }
- case 's': {
- saltLength = Integer.parseInt(args[argIndex + 1]);
- break;
- }
- case 'k': {
- keyLength = Integer.parseInt(args[argIndex + 1]);
- break;
- }
- case 'h': {
- handlerClassName = args[argIndex + 1];
- break;
- }
- default: {
- usage();
- return;
- }
+ case 'a': {
+ algorithm = args[argIndex + 1];
+ break;
+ }
+ case 'e': {
+ encoding = args[argIndex + 1];
+ break;
+ }
+ case 'i': {
+ iterations = Integer.parseInt(args[argIndex + 1]);
+ break;
+ }
+ case 's': {
+ saltLength = Integer.parseInt(args[argIndex + 1]);
+ break;
+ }
+ case 'k': {
+ keyLength = Integer.parseInt(args[argIndex + 1]);
+ break;
+ }
+ case 'h': {
+ handlerClassName = args[argIndex + 1];
+ break;
+ }
+ default: {
+ usage();
+ return;
+ }
}
argIndex += 2;
}
@@ -1386,12 +1334,12 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
// Determine defaults for -a and -h. The rules are more complex to
// express than the implementation:
// - if neither -a nor -h is set, use SHA-512 and
- // MessageDigestCredentialHandler
+ // MessageDigestCredentialHandler
// - if only -a is set the built-in handlers will be searched in order
- // (MessageDigestCredentialHandler, SecretKeyCredentialHandler) and
- // the first handler that supports the algorithm will be used
+ // (MessageDigestCredentialHandler, SecretKeyCredentialHandler) and
+ // the first handler that supports the algorithm will be used
// - if only -h is set no default will be used for -a. The handler may
- // or may nor support -a and may or may not supply a sensible default
+ // or may nor support -a and may or may not supply a sensible default
if (algorithm == null && handlerClassName == null) {
algorithm = "SHA-512";
}
@@ -1445,12 +1393,11 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
private static void usage() {
System.out.println("Usage: RealmBase [-a <algorithm>] [-e <encoding>] " +
- "[-i <iterations>] [-s <salt-length>] [-k <key-length>] " +
- "[-h <handler-class-name>] <credentials>");
+ "[-i <iterations>] [-s <salt-length>] [-k <key-length>] " + "[-h <handler-class-name>] <credentials>");
}
- // -------------------- JMX and Registration --------------------
+ // -------------------- JMX and Registration --------------------
@Override
public String getObjectNameKeyProperties() {
@@ -1486,15 +1433,14 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
private final String name;
/**
- * Use the strict servlet spec interpretation which requires that the user
- * have one of the web-app/security-role/role-name
+ * Use the strict servlet spec interpretation which requires that the user have one of the
+ * web-app/security-role/role-name
*/
public static final AllRolesMode STRICT_MODE = new AllRolesMode("strict");
/** Allow any authenticated user */
public static final AllRolesMode AUTH_ONLY_MODE = new AllRolesMode("authOnly");
/**
- * Allow any authenticated user only if there are no
- * web-app/security-roles
+ * Allow any authenticated user only if there are no web-app/security-roles
*/
public static final AllRolesMode STRICT_AUTH_ONLY_MODE = new AllRolesMode("strictAuthOnly");
@@ -1507,8 +1453,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
} else if (name.equalsIgnoreCase(STRICT_AUTH_ONLY_MODE.name)) {
mode = STRICT_AUTH_ONLY_MODE;
} else {
- throw new IllegalStateException(
- sm.getString("realmBase.unknownAllRolesMode", name));
+ throw new IllegalStateException(sm.getString("realmBase.unknownAllRolesMode", name));
}
return mode;
}
@@ -1538,20 +1483,21 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
}
}
- private static X509UsernameRetriever createUsernameRetriever(String className)
- throws LifecycleException {
- if(null == className || className.trim().isEmpty()) {
+ private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException {
+ if (null == className || className.trim().isEmpty()) {
return new X509SubjectDnRetriever();
}
try {
@SuppressWarnings("unchecked")
- Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className);
+ Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>) Class
+ .forName(className);
return clazz.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.newInstance", className), e);
} catch (ClassCastException e) {
- throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e);
+ throw new LifecycleException(
+ sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e);
}
}
}
diff --git a/java/org/apache/catalina/realm/UserDatabaseRealm.java b/java/org/apache/catalina/realm/UserDatabaseRealm.java
index c8aff94807..f8dc9866ac 100644
--- a/java/org/apache/catalina/realm/UserDatabaseRealm.java
+++ b/java/org/apache/catalina/realm/UserDatabaseRealm.java
@@ -34,13 +34,12 @@ import org.apache.naming.ContextBindings;
import org.apache.tomcat.util.ExceptionUtils;
/**
- * Implementation of {@link org.apache.catalina.Realm} that is based on an
- * implementation of {@link UserDatabase} made available through the JNDI
- * resources configured for this instance of Catalina. Set the
- * <code>resourceName</code> parameter to the JNDI resources name for the
- * configured instance of <code>UserDatabase</code> that we should consult.
+ * Implementation of {@link org.apache.catalina.Realm} that is based on an implementation of {@link UserDatabase} made
+ * available through the JNDI resources configured for this instance of Catalina. Set the <code>resourceName</code>
+ * parameter to the JNDI resources name for the configured instance of <code>UserDatabase</code> that we should consult.
*
* @author Craig R. McClanahan
+ *
* @since 4.1
*/
public class UserDatabaseRealm extends RealmBase {
@@ -48,15 +47,13 @@ public class UserDatabaseRealm extends RealmBase {
// ----------------------------------------------------- Instance Variables
/**
- * The <code>UserDatabase</code> we will use to authenticate users and
- * identify associated roles.
+ * The <code>UserDatabase</code> we will use to authenticate users and identify associated roles.
*/
protected volatile UserDatabase database = null;
private final Object databaseLock = new Object();
/**
- * The global JNDI name of the <code>UserDatabase</code> resource we will be
- * utilizing.
+ * The global JNDI name of the <code>UserDatabase</code> resource we will be utilizing.
*/
protected String resourceName = "UserDatabase";
@@ -66,9 +63,8 @@ public class UserDatabaseRealm extends RealmBase {
private boolean localJndiResource = false;
/**
- * Use a static principal disconnected from the database. This prevents live
- * updates to users and roles having an effect on authenticated principals,
- * but reduces use of the database.
+ * Use a static principal disconnected from the database. This prevents live updates to users and roles having an
+ * effect on authenticated principals, but reduces use of the database.
*/
private boolean useStaticPrincipal = false;
@@ -76,8 +72,7 @@ public class UserDatabaseRealm extends RealmBase {
// ------------------------------------------------------------- Properties
/**
- * @return the global JNDI name of the <code>UserDatabase</code> resource we
- * will be using.
+ * @return the global JNDI name of the <code>UserDatabase</code> resource we will be using.
*/
public String getResourceName() {
return resourceName;
@@ -85,8 +80,7 @@ public class UserDatabaseRealm extends RealmBase {
/**
- * Set the global JNDI name of the <code>UserDatabase</code> resource we
- * will be using.
+ * Set the global JNDI name of the <code>UserDatabase</code> resource we will be using.
*
* @param resourceName The new global JNDI name
*/
@@ -105,6 +99,7 @@ public class UserDatabaseRealm extends RealmBase {
/**
* Allows using a static principal disconnected from the user database.
+ *
* @param useStaticPrincipal the new value
*/
public void setUseStaticPrincipal(boolean useStaticPrincipal) {
@@ -113,12 +108,11 @@ public class UserDatabaseRealm extends RealmBase {
/**
- * Determines whether this Realm is configured to obtain the associated
- * {@link UserDatabase} from the global JNDI context or a local (web
- * application) JNDI context.
+ * Determines whether this Realm is configured to obtain the associated {@link UserDatabase} from the global JNDI
+ * context or a local (web application) JNDI context.
*
- * @return {@code true} if a local JNDI context will be used, {@code false}
- * if the the global JNDI context will be used
+ * @return {@code true} if a local JNDI context will be used, {@code false} if the the global JNDI context will be
+ * used
*/
public boolean getLocalJndiResource() {
return localJndiResource;
@@ -126,11 +120,10 @@ public class UserDatabaseRealm extends RealmBase {
/**
- * Configure whether this Realm obtains the associated {@link UserDatabase}
- * from the global JNDI context or a local (web application) JNDI context.
+ * Configure whether this Realm obtains the associated {@link UserDatabase} from the global JNDI context or a local
+ * (web application) JNDI context.
*
- * @param localJndiResource {@code true} to use a local JNDI context,
- * {@code false} to use the global JNDI context
+ * @param localJndiResource {@code true} to use a local JNDI context, {@code false} to use the global JNDI context
*/
public void setLocalJndiResource(boolean localJndiResource) {
this.localJndiResource = localJndiResource;
@@ -211,8 +204,7 @@ public class UserDatabaseRealm extends RealmBase {
/*
- * Can't do this in startInternal() with local JNDI as the local JNDI
- * context won't be initialised at this point.
+ * Can't do this in startInternal() with local JNDI as the local JNDI context won't be initialised at this point.
*/
private UserDatabase getUserDatabase() {
// DCL so database MUST be volatile
@@ -261,12 +253,10 @@ public class UserDatabaseRealm extends RealmBase {
/**
- * Gracefully terminate the active use of the public methods of this
- * component and implement the requirements of
+ * Gracefully terminate the active use of the public methods of this component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
- * @exception LifecycleException if this component detects a fatal error
- * that needs to be reported
+ * @exception LifecycleException if this component detects a fatal error that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
diff --git a/java/org/apache/catalina/realm/X509SubjectDnRetriever.java b/java/org/apache/catalina/realm/X509SubjectDnRetriever.java
index 6636e810a1..f8d3a4a976 100644
--- a/java/org/apache/catalina/realm/X509SubjectDnRetriever.java
+++ b/java/org/apache/catalina/realm/X509SubjectDnRetriever.java
@@ -19,8 +19,7 @@ package org.apache.catalina.realm;
import java.security.cert.X509Certificate;
/**
- * An X509UsernameRetriever that returns a certificate's entire
- * SubjectDN as the username.
+ * An X509UsernameRetriever that returns a certificate's entire SubjectDN as the username.
*/
public class X509SubjectDnRetriever implements X509UsernameRetriever {
diff --git a/java/org/apache/catalina/realm/X509UsernameRetriever.java b/java/org/apache/catalina/realm/X509UsernameRetriever.java
index 671fe08d86..d4bc630b3a 100644
--- a/java/org/apache/catalina/realm/X509UsernameRetriever.java
+++ b/java/org/apache/catalina/realm/X509UsernameRetriever.java
@@ -26,8 +26,8 @@ public interface X509UsernameRetriever {
* Gets a user name from an X509Certificate.
*
* @param cert The certificate containing the user name.
- * @return An appropriate user name obtained from one or more fields
- * in the certificate.
+ *
+ * @return An appropriate user name obtained from one or more fields in the certificate.
*/
public String getUsername(X509Certificate cert);
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org