You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ss...@apache.org on 2025/03/28 14:07:35 UTC
(sling-org-apache-sling-auth-core) 02/02: SLING-12727 apply spotless formatting
This is an automated email from the ASF dual-hosted git repository.
sseifert pushed a commit to branch feature/SLING-12727-parent-62
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-core.git
commit 7c6ee4a99363dc47b72cc8c5cc388e8c98fb7094
Author: Stefan Seifert <st...@users.noreply.github.com>
AuthorDate: Fri Mar 28 15:07:08 2025 +0100
SLING-12727 apply spotless formatting
---
pom.xml | 34 +-
.../org/apache/sling/auth/core/AuthConstants.java | 20 +-
.../java/org/apache/sling/auth/core/AuthUtil.java | 136 +++---
.../sling/auth/core/AuthenticationSupport.java | 8 +-
.../auth/core/JakartaLoginEventDecorator.java | 40 +-
.../sling/auth/core/LoginEventDecorator.java | 43 +-
.../impl/AbstractAuthenticationHandlerHolder.java | 37 +-
.../core/impl/AuthenticationHandlerHolder.java | 44 +-
.../core/impl/AuthenticationHandlerWrapper.java | 48 +-
.../core/impl/AuthenticationHandlersManager.java | 57 ++-
.../core/impl/AuthenticationRequirementHolder.java | 24 +-
.../impl/AuthenticationRequirementsManager.java | 162 +++----
.../core/impl/AuthenticatorWebConsolePlugin.java | 24 +-
.../sling/auth/core/impl/FailureCodesMapper.java | 3 +-
.../core/impl/HttpBasicAuthenticationHandler.java | 43 +-
.../apache/sling/auth/core/impl/LoginServlet.java | 27 +-
.../apache/sling/auth/core/impl/LogoutServlet.java | 13 +-
.../sling/auth/core/impl/PathBasedHolder.java | 24 +-
.../sling/auth/core/impl/PathBasedHolderCache.java | 9 +-
.../auth/core/impl/SlingAuthenticationMetrics.java | 28 +-
.../sling/auth/core/impl/SlingAuthenticator.java | 498 +++++++++++----------
.../engine/EngineAuthenticationHandlerHolder.java | 66 ++-
.../core/impl/engine/EngineSlingAuthenticator.java | 1 -
.../core/impl/hc/DefaultLoginsHealthCheck.java | 43 +-
.../org/apache/sling/auth/core/package-info.java | 2 -
.../spi/AbstractAuthenticationFormServlet.java | 23 +-
.../core/spi/AbstractAuthenticationHandler.java | 22 +-
.../AbstractJakartaAuthenticationFormServlet.java | 16 +-
.../core/spi/AuthenticationFeedbackHandler.java | 7 +-
.../sling/auth/core/spi/AuthenticationHandler.java | 14 +-
.../sling/auth/core/spi/AuthenticationInfo.java | 46 +-
.../core/spi/AuthenticationInfoPostProcessor.java | 29 +-
.../spi/DefaultAuthenticationFeedbackHandler.java | 32 +-
...efaultJakartaAuthenticationFeedbackHandler.java | 33 +-
.../spi/JakartaAuthenticationFeedbackHandler.java | 8 +-
.../core/spi/JakartaAuthenticationHandler.java | 10 +-
.../JakartaAuthenticationInfoPostProcessor.java | 30 +-
.../apache/sling/auth/core/spi/package-info.java | 2 -
.../sling/engine/auth/AuthenticationHandler.java | 10 +-
.../sling/engine/auth/AuthenticationInfo.java | 3 +-
.../apache/sling/engine/auth/Authenticator.java | 1 -
.../auth/NoAuthenticationHandlerException.java | 1 -
.../org/apache/sling/engine/auth/package-info.java | 2 -
.../org/apache/sling/auth/core/AuthUtilTest.java | 45 +-
.../impl/AuthenticationHandlersManagerTest.java | 208 +++++----
.../AuthenticationRequirementsManagerTest.java | 298 +++++++-----
.../auth/core/impl/FailureCodesMapperTest.java | 34 +-
.../sling/auth/core/impl/PathBasedHolderTest.java | 18 +-
.../core/impl/SlingAuthenticationMetricsTest.java | 34 +-
.../core/impl/SlingAuthenticatorOsgiJavaxTest.java | 105 +++--
.../auth/core/impl/SlingAuthenticatorOsgiTest.java | 105 ++---
.../auth/core/impl/SlingAuthenticatorTest.java | 113 ++---
.../core/impl/hc/DefaultLoginsHealthCheckTest.java | 42 +-
.../apache/sling/auth/core/impl/hc/SetField.java | 18 +-
.../auth/core/spi/AuthenticationInfoTest.java | 48 +-
.../core/spi/ReadOnlyAuthenticationInfoTest.java | 17 +-
56 files changed, 1463 insertions(+), 1345 deletions(-)
diff --git a/pom.xml b/pom.xml
index 4470f5f..d8d4b78 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
+<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@@ -31,13 +31,18 @@
<version>2.0.0-SNAPSHOT</version>
<name>Apache Sling Auth Core</name>
- <description>
- The Sling Authentication Service bundle provides the basic
+ <description>The Sling Authentication Service bundle provides the basic
mechanisms to authenticate HTTP requests with a JCR repository.
The algorithms for extracting authentication details from the
requests is extensible by implementing an AuthenticationHandler
- interface.
- </description>
+ interface.</description>
+
+ <scm>
+ <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-core.git</connection>
+ <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-core.git</developerConnection>
+ <tag>HEAD</tag>
+ <url>https://github.com/apache/sling-org-apache-sling-auth-core.git</url>
+ </scm>
<properties>
<site.jira.version.id>12315268</site.jira.version.id>
@@ -46,20 +51,13 @@
<project.build.outputTimestamp>2023-10-04T05:43:57Z</project.build.outputTimestamp>
</properties>
- <scm>
- <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-core.git</connection>
- <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-core.git</developerConnection>
- <url>https://github.com/apache/sling-org-apache-sling-auth-core.git</url>
- <tag>HEAD</tag>
- </scm>
-
- <dependencies>
- <dependency>
+ <dependencies>
+ <dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.annotation.versioning</artifactId>
<scope>provided</scope>
- </dependency>
- <dependency>
+ </dependency>
+ <dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.annotation.bundle</artifactId>
<scope>provided</scope>
@@ -156,7 +154,7 @@
<version>1.2.8</version>
<scope>provided</scope>
</dependency>
- <dependency>
+ <dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<scope>provided</scope>
@@ -209,7 +207,7 @@
<version>3.1.0</version>
<scope>test</scope>
</dependency>
- <dependency>
+ <dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>4.2.0</version>
diff --git a/src/main/java/org/apache/sling/auth/core/AuthConstants.java b/src/main/java/org/apache/sling/auth/core/AuthConstants.java
index 7b39bc4..b3ab25b 100644
--- a/src/main/java/org/apache/sling/auth/core/AuthConstants.java
+++ b/src/main/java/org/apache/sling/auth/core/AuthConstants.java
@@ -135,17 +135,15 @@ public final class AuthConstants {
public static final String AUTH_REQUIREMENTS = "sling.auth.requirements";
/**
- * The name of the request attribute containing the list of
- * request URI suffixes handled by the default authenticator
- * <code>org.apache.sling.auth.core.impl.SlingAuthenticator</code>.
- * The authenticator will populate this attribute so that login JSPs
- * can post j_username and j_password to the correct URI.
- *
- * @since 1.3.2 (bundle version 1.4.0)
- */
+ * The name of the request attribute containing the list of
+ * request URI suffixes handled by the default authenticator
+ * <code>org.apache.sling.auth.core.impl.SlingAuthenticator</code>.
+ * The authenticator will populate this attribute so that login JSPs
+ * can post j_username and j_password to the correct URI.
+ *
+ * @since 1.3.2 (bundle version 1.4.0)
+ */
public static final String ATTR_REQUEST_AUTH_URI_SUFFIX = "org.apache.sling.api.include.auth_uri_suffix";
- private AuthConstants() {
- }
-
+ private AuthConstants() {}
}
diff --git a/src/main/java/org/apache/sling/auth/core/AuthUtil.java b/src/main/java/org/apache/sling/auth/core/AuthUtil.java
index 2d1ee50..b57c11f 100644
--- a/src/main/java/org/apache/sling/auth/core/AuthUtil.java
+++ b/src/main/java/org/apache/sling/auth/core/AuthUtil.java
@@ -33,7 +33,6 @@ import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.auth.Authenticator;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
@@ -94,8 +93,7 @@ public final class AuthUtil {
private static final String BROWSER_CLASS_OPERA = "Opera";
// no instantiation
- private AuthUtil() {
- }
+ private AuthUtil() {}
/**
* Returns the value of the named request attribute or parameter as a string
@@ -119,8 +117,7 @@ public final class AuthUtil {
* @since 1.6.0
*/
public static String getAttributeOrParameter(
- final HttpServletRequest request, final String name,
- final String defaultValue) {
+ final HttpServletRequest request, final String name, final String defaultValue) {
final String resourceAttr = getAttributeString(request, name);
if (resourceAttr != null) {
@@ -158,8 +155,7 @@ public final class AuthUtil {
*/
@Deprecated
public static String getAttributeOrParameter(
- final javax.servlet.http.HttpServletRequest request, final String name,
- final String defaultValue) {
+ final javax.servlet.http.HttpServletRequest request, final String name, final String defaultValue) {
final String resourceAttr = getAttributeString(request, name);
if (resourceAttr != null) {
@@ -188,10 +184,8 @@ public final class AuthUtil {
* <code>defaultLoginResource</code>.
* @since 1.6.0
*/
- public static String getLoginResource(final HttpServletRequest request,
- String defaultLoginResource) {
- return getAttributeOrParameter(request, Authenticator.LOGIN_RESOURCE,
- defaultLoginResource);
+ public static String getLoginResource(final HttpServletRequest request, String defaultLoginResource) {
+ return getAttributeOrParameter(request, Authenticator.LOGIN_RESOURCE, defaultLoginResource);
}
/**
@@ -209,10 +203,9 @@ public final class AuthUtil {
* @deprecated Use {@link #getLoginResource(HttpServletRequest, String)}
*/
@Deprecated
- public static String getLoginResource(final javax.servlet.http.HttpServletRequest request,
- String defaultLoginResource) {
- return getAttributeOrParameter(request, Authenticator.LOGIN_RESOURCE,
- defaultLoginResource);
+ public static String getLoginResource(
+ final javax.servlet.http.HttpServletRequest request, String defaultLoginResource) {
+ return getAttributeOrParameter(request, Authenticator.LOGIN_RESOURCE, defaultLoginResource);
}
/**
@@ -234,10 +227,8 @@ public final class AuthUtil {
* @return returns the value of resource request attribute
* @since 1.6.0
*/
- public static String setLoginResourceAttribute(
- final HttpServletRequest request, final String defaultValue) {
- String resourceAttr = getAttributeString(request,
- Authenticator.LOGIN_RESOURCE);
+ public static String setLoginResourceAttribute(final HttpServletRequest request, final String defaultValue) {
+ String resourceAttr = getAttributeString(request, Authenticator.LOGIN_RESOURCE);
if (resourceAttr == null) {
final String resourcePar = request.getParameter(Authenticator.LOGIN_RESOURCE);
if (resourcePar != null && resourcePar.length() > 0) {
@@ -274,8 +265,7 @@ public final class AuthUtil {
@Deprecated
public static String setLoginResourceAttribute(
final javax.servlet.http.HttpServletRequest request, final String defaultValue) {
- String resourceAttr = getAttributeString(request,
- Authenticator.LOGIN_RESOURCE);
+ String resourceAttr = getAttributeString(request, Authenticator.LOGIN_RESOURCE);
if (resourceAttr == null) {
final String resourcePar = request.getParameter(Authenticator.LOGIN_RESOURCE);
if (resourcePar != null && resourcePar.length() > 0) {
@@ -334,9 +324,12 @@ public final class AuthUtil {
* missing.
* @since 1.6.0
*/
- public static void sendRedirect(final HttpServletRequest request,
- final HttpServletResponse response, final String target,
- Map<String, String> params) throws IOException {
+ public static void sendRedirect(
+ final HttpServletRequest request,
+ final HttpServletResponse response,
+ final String target,
+ Map<String, String> params)
+ throws IOException {
checkAndReset(response);
@@ -368,11 +361,9 @@ public final class AuthUtil {
Entry<String, String> entry = ei.next();
if (entry.getKey() != null && entry.getValue() != null) {
try {
- b.append(entry.getKey()).append('=').append(
- URLEncoder.encode(entry.getValue(), "UTF-8"));
+ b.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException uee) {
- throw new InternalError(
- "Unexpected UnsupportedEncodingException for UTF-8");
+ throw new InternalError("Unexpected UnsupportedEncodingException for UTF-8");
}
if (ei.hasNext()) {
@@ -429,9 +420,12 @@ public final class AuthUtil {
* @deprecated Use {@link #sendRedirect(HttpServletRequest, HttpServletResponse, String, Map)}
*/
@Deprecated
- public static void sendRedirect(final javax.servlet.http.HttpServletRequest request,
- final javax.servlet.http.HttpServletResponse response, final String target,
- Map<String, String> params) throws IOException {
+ public static void sendRedirect(
+ final javax.servlet.http.HttpServletRequest request,
+ final javax.servlet.http.HttpServletResponse response,
+ final String target,
+ Map<String, String> params)
+ throws IOException {
checkAndReset(response);
@@ -463,11 +457,9 @@ public final class AuthUtil {
Entry<String, String> entry = ei.next();
if (entry.getKey() != null && entry.getValue() != null) {
try {
- b.append(entry.getKey()).append('=').append(
- URLEncoder.encode(entry.getValue(), "UTF-8"));
+ b.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException uee) {
- throw new InternalError(
- "Unexpected UnsupportedEncodingException for UTF-8");
+ throw new InternalError("Unexpected UnsupportedEncodingException for UTF-8");
}
if (ei.hasNext()) {
@@ -487,8 +479,7 @@ public final class AuthUtil {
* @return The named request attribute or <code>null</code> if the attribute
* is not set or is not a non-empty string value.
*/
- private static String getAttributeString(final HttpServletRequest request,
- final String name) {
+ private static String getAttributeString(final HttpServletRequest request, final String name) {
Object resObj = request.getAttribute(name);
if ((resObj instanceof String) && ((String) resObj).length() > 0) {
return (String) resObj;
@@ -506,8 +497,7 @@ public final class AuthUtil {
* @return The named request attribute or <code>null</code> if the attribute
* is not set or is not a non-empty string value.
*/
- private static String getAttributeString(final javax.servlet.http.HttpServletRequest request,
- final String name) {
+ private static String getAttributeString(final javax.servlet.http.HttpServletRequest request, final String name) {
Object resObj = request.getAttribute(name);
if ((resObj instanceof String) && ((String) resObj).length() > 0) {
return (String) resObj;
@@ -641,8 +631,7 @@ public final class AuthUtil {
* @throws IllegalStateException if the response has already been committed
* @since 1.6.0
*/
- public static void sendInvalid(final HttpServletRequest request,
- final HttpServletResponse response) {
+ public static void sendInvalid(final HttpServletRequest request, final HttpServletResponse response) {
checkAndReset(response);
try {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
@@ -651,7 +640,7 @@ public final class AuthUtil {
Object reasonCode = request.getAttribute(JakartaAuthenticationHandler.FAILURE_REASON_CODE);
if (reason != null) {
response.setHeader(AuthConstants.X_REASON, reason.toString());
- if ( reasonCode != null ) {
+ if (reasonCode != null) {
response.setHeader(AuthConstants.X_REASON_CODE, reasonCode.toString());
}
response.setContentType("text/plain");
@@ -682,7 +671,8 @@ public final class AuthUtil {
* @deprecated Use {@link #sendInvalid(HttpServletRequest, HttpServletResponse)}
*/
@Deprecated
- public static void sendInvalid(final javax.servlet.http.HttpServletRequest request,
+ public static void sendInvalid(
+ final javax.servlet.http.HttpServletRequest request,
final javax.servlet.http.HttpServletResponse response) {
checkAndReset(response);
try {
@@ -692,7 +682,7 @@ public final class AuthUtil {
Object reasonCode = request.getAttribute(JakartaAuthenticationHandler.FAILURE_REASON_CODE);
if (reason != null) {
response.setHeader(AuthConstants.X_REASON, reason.toString());
- if ( reasonCode != null ) {
+ if (reasonCode != null) {
response.setHeader(AuthConstants.X_REASON_CODE, reasonCode.toString());
}
response.setContentType("text/plain");
@@ -715,22 +705,22 @@ public final class AuthUtil {
* @since 1.6.0
*/
public static boolean checkReferer(HttpServletRequest request, String loginForm) {
- //SLING-2165: if a Referrer header is supplied check if it matches the login path for this handler
- if ("POST".equals(request.getMethod())) {
+ // SLING-2165: if a Referrer header is supplied check if it matches the login path for this handler
+ if ("POST".equals(request.getMethod())) {
String referer = request.getHeader("Referer");
if (referer != null) {
String expectedPath = String.format("%s%s", request.getContextPath(), loginForm);
try {
URL uri = new URL(referer);
if (!expectedPath.equals(uri.getPath())) {
- //not for this selector, so let the next one handle it.
+ // not for this selector, so let the next one handle it.
return false;
}
} catch (MalformedURLException e) {
getLog().debug("Failed to parse the referer value for the login form " + loginForm, e);
}
}
- }
+ }
return true;
}
@@ -744,22 +734,22 @@ public final class AuthUtil {
*/
@Deprecated
public static boolean checkReferer(javax.servlet.http.HttpServletRequest request, String loginForm) {
- //SLING-2165: if a Referrer header is supplied check if it matches the login path for this handler
- if ("POST".equals(request.getMethod())) {
+ // SLING-2165: if a Referrer header is supplied check if it matches the login path for this handler
+ if ("POST".equals(request.getMethod())) {
String referer = request.getHeader("Referer");
if (referer != null) {
String expectedPath = String.format("%s%s", request.getContextPath(), loginForm);
try {
URL uri = new URL(referer);
if (!expectedPath.equals(uri.getPath())) {
- //not for this selector, so let the next one handle it.
+ // not for this selector, so let the next one handle it.
return false;
}
} catch (MalformedURLException e) {
getLog().debug("Failed to parse the referer value for the login form " + loginForm, e);
}
}
- }
+ }
return true;
}
@@ -817,16 +807,21 @@ public final class AuthUtil {
return false;
}
- if (target.contains("//") || target.contains("/../") || target.contains("/./") || target.endsWith("/.")
- || target.endsWith("/..")) {
+ if (target.contains("//")
+ || target.contains("/../")
+ || target.contains("/./")
+ || target.endsWith("/.")
+ || target.endsWith("/..")) {
getLog().warn("isRedirectValid: Redirect target '{}' is not normalized", target);
return false;
}
final String ctxPath = getContextPath(request);
if (ctxPath.length() > 0 && !target.startsWith(ctxPath)) {
- getLog().warn("isRedirectValid: Redirect target '{}' does not start with servlet context path '{}'",
- target, ctxPath);
+ getLog().warn(
+ "isRedirectValid: Redirect target '{}' does not start with servlet context path '{}'",
+ target,
+ ctxPath);
return false;
}
@@ -838,8 +833,9 @@ public final class AuthUtil {
final String localTarget = target.substring(ctxPath.length());
if (!localTarget.startsWith("/")) {
getLog().warn(
- "isRedirectValid: Redirect target '{}' without servlet context path '{}' must be an absolute path",
- target, ctxPath);
+ "isRedirectValid: Redirect target '{}' without servlet context path '{}' must be an absolute path",
+ target,
+ ctxPath);
return false;
}
@@ -917,16 +913,21 @@ public final class AuthUtil {
return false;
}
- if (target.contains("//") || target.contains("/../") || target.contains("/./") || target.endsWith("/.")
- || target.endsWith("/..")) {
+ if (target.contains("//")
+ || target.contains("/../")
+ || target.contains("/./")
+ || target.endsWith("/.")
+ || target.endsWith("/..")) {
getLog().warn("isRedirectValid: Redirect target '{}' is not normalized", target);
return false;
}
final String ctxPath = getContextPath(request);
if (ctxPath.length() > 0 && !target.startsWith(ctxPath)) {
- getLog().warn("isRedirectValid: Redirect target '{}' does not start with servlet context path '{}'",
- target, ctxPath);
+ getLog().warn(
+ "isRedirectValid: Redirect target '{}' does not start with servlet context path '{}'",
+ target,
+ ctxPath);
return false;
}
@@ -938,8 +939,9 @@ public final class AuthUtil {
final String localTarget = target.substring(ctxPath.length());
if (!localTarget.startsWith("/")) {
getLog().warn(
- "isRedirectValid: Redirect target '{}' without servlet context path '{}' must be an absolute path",
- target, ctxPath);
+ "isRedirectValid: Redirect target '{}' without servlet context path '{}' must be an absolute path",
+ target,
+ ctxPath);
return false;
}
@@ -1027,7 +1029,8 @@ public final class AuthUtil {
*/
public static boolean isBrowserRequest(final HttpServletRequest request) {
final String userAgent = request.getHeader(USER_AGENT);
- return userAgent != null && (userAgent.contains(BROWSER_CLASS_MOZILLA) || userAgent.contains(BROWSER_CLASS_OPERA));
+ return userAgent != null
+ && (userAgent.contains(BROWSER_CLASS_MOZILLA) || userAgent.contains(BROWSER_CLASS_OPERA));
}
/**
@@ -1048,7 +1051,8 @@ public final class AuthUtil {
@Deprecated
public static boolean isBrowserRequest(final javax.servlet.http.HttpServletRequest request) {
final String userAgent = request.getHeader(USER_AGENT);
- return userAgent != null && (userAgent.contains(BROWSER_CLASS_MOZILLA) || userAgent.contains(BROWSER_CLASS_OPERA));
+ return userAgent != null
+ && (userAgent.contains(BROWSER_CLASS_MOZILLA) || userAgent.contains(BROWSER_CLASS_OPERA));
}
/**
diff --git a/src/main/java/org/apache/sling/auth/core/AuthenticationSupport.java b/src/main/java/org/apache/sling/auth/core/AuthenticationSupport.java
index ce4f20b..999fed0 100644
--- a/src/main/java/org/apache/sling/auth/core/AuthenticationSupport.java
+++ b/src/main/java/org/apache/sling/auth/core/AuthenticationSupport.java
@@ -20,7 +20,6 @@ package org.apache.sling.auth.core;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.osgi.annotation.versioning.ProviderType;
/**
@@ -117,8 +116,7 @@ public interface AuthenticationSupport {
* is immediately terminated and no request attributes are set.
* @since 1.6.0
*/
- boolean handleSecurity(HttpServletRequest request,
- HttpServletResponse response);
+ boolean handleSecurity(HttpServletRequest request, HttpServletResponse response);
/**
* Handles security on behalf of a custom OSGi Http Service
@@ -139,6 +137,6 @@ public interface AuthenticationSupport {
* @deprecated Use {@link #handleSecurity(HttpServletRequest, HttpServletResponse)}
*/
@Deprecated
- boolean handleSecurity(javax.servlet.http.HttpServletRequest request,
- javax.servlet.http.HttpServletResponse response);
+ boolean handleSecurity(
+ javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response);
}
diff --git a/src/main/java/org/apache/sling/auth/core/JakartaLoginEventDecorator.java b/src/main/java/org/apache/sling/auth/core/JakartaLoginEventDecorator.java
index eb20d70..6637899 100644
--- a/src/main/java/org/apache/sling/auth/core/JakartaLoginEventDecorator.java
+++ b/src/main/java/org/apache/sling/auth/core/JakartaLoginEventDecorator.java
@@ -1,25 +1,26 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
-
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.jetbrains.annotations.NotNull;
import org.osgi.annotation.versioning.ConsumerType;
@@ -39,10 +40,12 @@ public interface JakartaLoginEventDecorator {
* @param authInfo the current authInfo
* @param eventProperties the event properties to decorate
*/
- @NotNull default void decorateLoginEvent(final @NotNull HttpServletRequest request,
+ @NotNull
+ default void decorateLoginEvent(
+ final @NotNull HttpServletRequest request,
final @NotNull AuthenticationInfo authInfo,
final @NotNull Map<String, Object> eventProperties) {
- //no-op
+ // no-op
}
/**
@@ -52,10 +55,11 @@ public interface JakartaLoginEventDecorator {
* @param authInfo the current authInfo
* @param eventProperties the event properties to decorate
*/
- @NotNull default void decorateLoginFailedEvent(final @NotNull HttpServletRequest request,
+ @NotNull
+ default void decorateLoginFailedEvent(
+ final @NotNull HttpServletRequest request,
final @NotNull AuthenticationInfo authInfo,
final @NotNull Map<String, Object> eventProperties) {
- //no-op
+ // no-op
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/LoginEventDecorator.java b/src/main/java/org/apache/sling/auth/core/LoginEventDecorator.java
index 081b171..0ee0a1e 100644
--- a/src/main/java/org/apache/sling/auth/core/LoginEventDecorator.java
+++ b/src/main/java/org/apache/sling/auth/core/LoginEventDecorator.java
@@ -1,25 +1,27 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core;
-import java.util.Map;
-
import javax.servlet.http.HttpServletRequest;
+import java.util.Map;
+
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.jetbrains.annotations.NotNull;
import org.osgi.annotation.versioning.ConsumerType;
@@ -40,10 +42,12 @@ public interface LoginEventDecorator {
* @param authInfo the current authInfo
* @param eventProperties the event properties to decorate
*/
- @NotNull default void decorateLoginEvent(final @NotNull HttpServletRequest request,
+ @NotNull
+ default void decorateLoginEvent(
+ final @NotNull HttpServletRequest request,
final @NotNull AuthenticationInfo authInfo,
final @NotNull Map<String, Object> eventProperties) {
- //no-op
+ // no-op
}
/**
@@ -53,10 +57,11 @@ public interface LoginEventDecorator {
* @param authInfo the current authInfo
* @param eventProperties the event properties to decorate
*/
- @NotNull default void decorateLoginFailedEvent(final @NotNull HttpServletRequest request,
+ @NotNull
+ default void decorateLoginFailedEvent(
+ final @NotNull HttpServletRequest request,
final @NotNull AuthenticationInfo authInfo,
final @NotNull Map<String, Object> eventProperties) {
- //no-op
+ // no-op
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AbstractAuthenticationHandlerHolder.java b/src/main/java/org/apache/sling/auth/core/impl/AbstractAuthenticationHandlerHolder.java
index 4d8fe98..af60637 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AbstractAuthenticationHandlerHolder.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AbstractAuthenticationHandlerHolder.java
@@ -22,7 +22,6 @@ import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.auth.core.spi.JakartaAuthenticationFeedbackHandler;
import org.apache.sling.auth.core.spi.JakartaAuthenticationHandler;
@@ -33,12 +32,10 @@ import org.osgi.framework.ServiceReference;
* represent authentication handlers (both legacy and new ones) for use in the
* {@link SlingAuthenticator}.
*/
-public abstract class AbstractAuthenticationHandlerHolder
- extends PathBasedHolder
+public abstract class AbstractAuthenticationHandlerHolder extends PathBasedHolder
implements JakartaAuthenticationHandler {
- protected AbstractAuthenticationHandlerHolder(final String fullPath,
- final ServiceReference<?> serviceReference) {
+ protected AbstractAuthenticationHandlerHolder(final String fullPath, final ServiceReference<?> serviceReference) {
super(fullPath, serviceReference);
}
@@ -53,8 +50,7 @@ public abstract class AbstractAuthenticationHandlerHolder
* @return the result of calling
* {@link #doExtractCredentials(HttpServletRequest, HttpServletResponse)}
*/
- public final AuthenticationInfo extractCredentials(
- HttpServletRequest request, HttpServletResponse response) {
+ public final AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response) {
final Object oldPathAttr = setPath(request);
try {
@@ -62,7 +58,6 @@ public abstract class AbstractAuthenticationHandlerHolder
} finally {
resetPath(request, oldPathAttr);
}
-
}
/**
@@ -77,8 +72,8 @@ public abstract class AbstractAuthenticationHandlerHolder
* {@link #doRequestCredentials(HttpServletRequest, HttpServletResponse)}
* @throws IOException if an error occurs interacting with the client
*/
- public final boolean requestCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public final boolean requestCredentials(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
final Object oldPathAttr = setPath(request);
try {
return doRequestCredentials(request, response);
@@ -97,8 +92,7 @@ public abstract class AbstractAuthenticationHandlerHolder
* @param response the current response
* @throws IOException if an error occurs interacting with the client
*/
- public final void dropCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public final void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
final Object oldPathAttr = setPath(request);
try {
doDropCredentials(request, response);
@@ -138,8 +132,8 @@ public abstract class AbstractAuthenticationHandlerHolder
* client.
* @see #requestCredentials(HttpServletRequest, HttpServletResponse)
*/
- protected abstract boolean doRequestCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ protected abstract boolean doRequestCredentials(HttpServletRequest request, HttpServletResponse response)
+ throws IOException;
/**
* Calls the actual authentication handler to request the credentials from
@@ -151,8 +145,8 @@ public abstract class AbstractAuthenticationHandlerHolder
* client.
* @see #dropCredentials(HttpServletRequest, HttpServletResponse)
*/
- protected abstract void doDropCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ protected abstract void doDropCredentials(HttpServletRequest request, HttpServletResponse response)
+ throws IOException;
// ---------- internal
@@ -161,8 +155,7 @@ public abstract class AbstractAuthenticationHandlerHolder
* {@link AuthenticationHandler#PATH_PROPERTY} request attribute.
*/
private Object setPath(final HttpServletRequest request) {
- return setRequestAttribute(request,
- JakartaAuthenticationHandler.PATH_PROPERTY, fullPath);
+ return setRequestAttribute(request, JakartaAuthenticationHandler.PATH_PROPERTY, fullPath);
}
/**
@@ -170,8 +163,7 @@ public abstract class AbstractAuthenticationHandlerHolder
* {@link AuthenticationHandler#PATH_PROPERTY} request attribute.
*/
private void resetPath(final HttpServletRequest request, Object oldValue) {
- setRequestAttribute(request, JakartaAuthenticationHandler.PATH_PROPERTY,
- oldValue);
+ setRequestAttribute(request, JakartaAuthenticationHandler.PATH_PROPERTY, oldValue);
}
/**
@@ -185,8 +177,7 @@ public abstract class AbstractAuthenticationHandlerHolder
* @return The previous value of the named request attribute or
* <code>null</code> if it was not set.
*/
- private static Object setRequestAttribute(HttpServletRequest request,
- String name, Object value) {
+ private static Object setRequestAttribute(HttpServletRequest request, String name, Object value) {
Object oldValue = request.getAttribute(name);
if (value == null) {
request.removeAttribute(name);
@@ -195,4 +186,4 @@ public abstract class AbstractAuthenticationHandlerHolder
}
return oldValue;
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerHolder.java b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerHolder.java
index e1e7f8e..ff3d1fe 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerHolder.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerHolder.java
@@ -23,7 +23,6 @@ import java.util.Objects;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.auth.core.AuthConstants;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
@@ -52,22 +51,28 @@ final class AuthenticationHandlerHolder extends AbstractAuthenticationHandlerHol
private Logger logger = LoggerFactory.getLogger(this.getClass());
- AuthenticationHandlerHolder(final String fullPath,
+ AuthenticationHandlerHolder(
+ final String fullPath,
final JakartaAuthenticationHandler handler,
final ServiceReference<?> serviceReference) {
super(fullPath, serviceReference);
- final String browserOnly = Converters.standardConverter().convert(serviceReference.getProperty(AuthConstants.AUTH_HANDLER_BROWSER_ONLY)).to(String.class);
+ final String browserOnly = Converters.standardConverter()
+ .convert(serviceReference.getProperty(AuthConstants.AUTH_HANDLER_BROWSER_ONLY))
+ .to(String.class);
// assign the fields
this.handler = handler;
- this.authType = Converters.standardConverter().convert(serviceReference.getProperty(JakartaAuthenticationHandler.TYPE_PROPERTY)).to(String.class);
- this.browserOnlyRequestCredentials = "true".equalsIgnoreCase(browserOnly)
- || "yes".equalsIgnoreCase(browserOnly);
+ this.authType = Converters.standardConverter()
+ .convert(serviceReference.getProperty(JakartaAuthenticationHandler.TYPE_PROPERTY))
+ .to(String.class);
+ this.browserOnlyRequestCredentials =
+ "true".equalsIgnoreCase(browserOnly) || "yes".equalsIgnoreCase(browserOnly);
}
- AuthenticationHandlerHolder(final String fullPath,
- @SuppressWarnings("deprecation") final org.apache.sling.auth.core.spi.AuthenticationHandler handler,
+ AuthenticationHandlerHolder(
+ final String fullPath,
+ @SuppressWarnings("deprecation") final org.apache.sling.auth.core.spi.AuthenticationHandler handler,
final ServiceReference<?> serviceReference) {
this(fullPath, AuthenticationHandlerWrapper.wrap(handler), serviceReference);
}
@@ -81,15 +86,13 @@ final class AuthenticationHandlerHolder extends AbstractAuthenticationHandlerHol
}
@Override
- public AuthenticationInfo doExtractCredentials(HttpServletRequest request,
- HttpServletResponse response) {
+ public AuthenticationInfo doExtractCredentials(HttpServletRequest request, HttpServletResponse response) {
this.logDebugMessage("doExtractCredentials", request);
return handler.extractCredentials(request, response);
}
@Override
- public boolean doRequestCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public boolean doRequestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
// call handler if ok by its authentication type
if (doesRequestCredentials(request)) {
@@ -102,8 +105,7 @@ final class AuthenticationHandlerHolder extends AbstractAuthenticationHandlerHol
}
@Override
- public void doDropCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void doDropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.logDebugMessage("doDropCredentials", request);
handler.dropCredentials(request, response);
}
@@ -118,12 +120,9 @@ final class AuthenticationHandlerHolder extends AbstractAuthenticationHandlerHol
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
+ if (getClass() != obj.getClass()) return false;
AuthenticationHandlerHolder other = (AuthenticationHandlerHolder) obj;
return Objects.equals(authType, other.authType)
&& browserOnlyRequestCredentials == other.browserOnlyRequestCredentials
@@ -173,8 +172,9 @@ final class AuthenticationHandlerHolder extends AbstractAuthenticationHandlerHol
private void logDebugMessage(String functionName, HttpServletRequest request) {
if (logger.isDebugEnabled()) {
- String message = functionName + ": Using AuthenticationHandler class {} to request credentials for request {} {}";
- logger.debug(message, handler, request.getMethod() ,request.getRequestURL());
+ String message =
+ functionName + ": Using AuthenticationHandler class {} to request credentials for request {} {}";
+ logger.debug(message, handler, request.getMethod(), request.getRequestURL());
}
}
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerWrapper.java b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerWrapper.java
index 610edf8..5fb36ea 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerWrapper.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlerWrapper.java
@@ -20,6 +20,8 @@ package org.apache.sling.auth.core.impl;
import java.io.IOException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.sling.api.wrappers.JakartaToJavaxRequestWrapper;
import org.apache.sling.api.wrappers.JakartaToJavaxResponseWrapper;
import org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler;
@@ -28,16 +30,12 @@ import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.auth.core.spi.JakartaAuthenticationFeedbackHandler;
import org.apache.sling.auth.core.spi.JakartaAuthenticationHandler;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
@SuppressWarnings("deprecation")
public class AuthenticationHandlerWrapper {
public static JakartaAuthenticationHandler wrap(final AuthenticationHandler handler) {
if (handler instanceof AuthenticationFeedbackHandler) {
return new FeedbackHandlerWrapper(handler);
-
}
return new HandlerWrapper(handler);
}
@@ -51,25 +49,27 @@ public class AuthenticationHandlerWrapper {
}
@Override
- public void dropCredentials(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
+ public void dropCredentials(final HttpServletRequest request, final HttpServletResponse response)
+ throws IOException {
handler.dropCredentials(
- JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response));
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response));
}
@Override
- public AuthenticationInfo extractCredentials(final HttpServletRequest request, final HttpServletResponse response) {
+ public AuthenticationInfo extractCredentials(
+ final HttpServletRequest request, final HttpServletResponse response) {
return handler.extractCredentials(
- JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response));
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response));
}
@Override
public boolean requestCredentials(final HttpServletRequest request, final HttpServletResponse response)
throws IOException {
return handler.requestCredentials(
- JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response));
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response));
}
}
@@ -79,23 +79,29 @@ public class AuthenticationHandlerWrapper {
FeedbackHandlerWrapper(final AuthenticationHandler handler) {
super(handler);
- this.handler = (AuthenticationFeedbackHandler)handler;
+ this.handler = (AuthenticationFeedbackHandler) handler;
}
-
@Override
- public void authenticationFailed(final HttpServletRequest request, final HttpServletResponse response,
+ public void authenticationFailed(
+ final HttpServletRequest request,
+ final HttpServletResponse response,
final AuthenticationInfo authInfo) {
- handler.authenticationFailed(JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response), authInfo);
+ handler.authenticationFailed(
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response),
+ authInfo);
}
-
@Override
- public boolean authenticationSucceeded(final HttpServletRequest request, final HttpServletResponse response,
+ public boolean authenticationSucceeded(
+ final HttpServletRequest request,
+ final HttpServletResponse response,
final AuthenticationInfo authInfo) {
- return handler.authenticationSucceeded(JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response), authInfo);
+ return handler.authenticationSucceeded(
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response),
+ authInfo);
}
}
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManager.java b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManager.java
index 221a14f..43b7dc9 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManager.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManager.java
@@ -37,8 +37,9 @@ import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.util.converter.Converters;
-@Component(service = {AuthenticationHandlersManager.class},
- configurationPid = SlingAuthenticator.PID)
+@Component(
+ service = {AuthenticationHandlersManager.class},
+ configurationPid = SlingAuthenticator.PID)
public class AuthenticationHandlersManager extends PathBasedHolderCache<AbstractAuthenticationHandlerHolder> {
/** Handler map for authentication handlers */
@@ -74,7 +75,7 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
if (httpSupport != null) {
final List<String> provider = ahMap.computeIfAbsent("/", key -> new ArrayList<>());
provider.add("HTTP Basic Authentication Handler ("
- + (Boolean.TRUE.equals(httpSupport) ? "enabled" : "preemptive") + ")");
+ + (Boolean.TRUE.equals(httpSupport) ? "enabled" : "preemptive") + ")");
}
return ahMap;
}
@@ -85,12 +86,13 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
* @param handler The handler
*/
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
- private void bindJakartaAuthHandler(final JakartaAuthenticationHandler handler, final ServiceReference<Object> ref) {
+ private void bindJakartaAuthHandler(
+ final JakartaAuthenticationHandler handler, final ServiceReference<Object> ref) {
final String id = "A".concat(ref.getProperty(Constants.SERVICE_ID).toString());
- final String[] paths = Converters.standardConverter().convert(ref.getProperty(JakartaAuthenticationHandler.PATH_PROPERTY)).to(String[].class);
- internalBindAuthHandler(paths, id, path -> new AuthenticationHandlerHolder(path,
- handler,
- ref));
+ final String[] paths = Converters.standardConverter()
+ .convert(ref.getProperty(JakartaAuthenticationHandler.PATH_PROPERTY))
+ .to(String[].class);
+ internalBindAuthHandler(paths, id, path -> new AuthenticationHandlerHolder(path, handler, ref));
}
/**
@@ -119,12 +121,14 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
* @param handler The handler
*/
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
- private void bindAuthHandler(@SuppressWarnings("deprecation") final org.apache.sling.auth.core.spi.AuthenticationHandler handler, final ServiceReference<Object> ref) {
+ private void bindAuthHandler(
+ @SuppressWarnings("deprecation") final org.apache.sling.auth.core.spi.AuthenticationHandler handler,
+ final ServiceReference<Object> ref) {
final String id = "A".concat(ref.getProperty(Constants.SERVICE_ID).toString());
- final String[] paths = Converters.standardConverter().convert(ref.getProperty(JakartaAuthenticationHandler.PATH_PROPERTY)).to(String[].class);
- internalBindAuthHandler(paths, id, path -> new AuthenticationHandlerHolder(path,
- handler,
- ref));
+ final String[] paths = Converters.standardConverter()
+ .convert(ref.getProperty(JakartaAuthenticationHandler.PATH_PROPERTY))
+ .to(String[].class);
+ internalBindAuthHandler(paths, id, path -> new AuthenticationHandlerHolder(path, handler, ref));
}
/**
@@ -133,7 +137,9 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
* @param handler The handler
*/
@SuppressWarnings("unused")
- private void updatedAuthHandler(@SuppressWarnings("deprecation") final org.apache.sling.auth.core.spi.AuthenticationHandler handler, final ServiceReference<Object> ref) {
+ private void updatedAuthHandler(
+ @SuppressWarnings("deprecation") final org.apache.sling.auth.core.spi.AuthenticationHandler handler,
+ final ServiceReference<Object> ref) {
unbindAuthHandler(ref);
bindAuthHandler(handler, ref);
}
@@ -155,12 +161,13 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
*/
@Deprecated
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
- private void bindEngineAuthHandler(final org.apache.sling.engine.auth.AuthenticationHandler handler, final ServiceReference<Object> ref) {
+ private void bindEngineAuthHandler(
+ final org.apache.sling.engine.auth.AuthenticationHandler handler, final ServiceReference<Object> ref) {
final String id = "E".concat(ref.getProperty(Constants.SERVICE_ID).toString());
- final String[] paths = Converters.standardConverter().convert(ref.getProperty(JakartaAuthenticationHandler.PATH_PROPERTY)).to(String[].class);
- internalBindAuthHandler(paths, id, path -> new EngineAuthenticationHandlerHolder(path,
- handler,
- ref));
+ final String[] paths = Converters.standardConverter()
+ .convert(ref.getProperty(JakartaAuthenticationHandler.PATH_PROPERTY))
+ .to(String[].class);
+ internalBindAuthHandler(paths, id, path -> new EngineAuthenticationHandlerHolder(path, handler, ref));
}
/**
@@ -171,7 +178,8 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
*/
@SuppressWarnings("unused")
@Deprecated
- private void updatedEngineAuthHandler(final org.apache.sling.engine.auth.AuthenticationHandler handler, final ServiceReference<Object> ref) {
+ private void updatedEngineAuthHandler(
+ final org.apache.sling.engine.auth.AuthenticationHandler handler, final ServiceReference<Object> ref) {
unbindEngineAuthHandler(ref);
bindEngineAuthHandler(handler, ref);
}
@@ -191,7 +199,10 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
* @param id Unique id
* @param createFunction Creation callback
*/
- private void internalBindAuthHandler(final String[] paths, final String id, final Function<String, AbstractAuthenticationHandlerHolder> createFunction) {
+ private void internalBindAuthHandler(
+ final String[] paths,
+ final String id,
+ final Function<String, AbstractAuthenticationHandlerHolder> createFunction) {
if (paths != null && paths.length > 0) {
// generate the holders
@@ -202,8 +213,8 @@ public class AuthenticationHandlersManager extends PathBasedHolderCache<Abstract
}
}
// register the holders
- if ( !holderList.isEmpty() ) {
- for(final AbstractAuthenticationHandlerHolder holder : holderList) {
+ if (!holderList.isEmpty()) {
+ for (final AbstractAuthenticationHandlerHolder holder : holderList) {
this.addHolder(holder);
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementHolder.java b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementHolder.java
index 52ea3df..748a9fc 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementHolder.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementHolder.java
@@ -24,11 +24,9 @@ class AuthenticationRequirementHolder extends PathBasedHolder {
private final boolean requiresAuthentication;
- static AuthenticationRequirementHolder fromConfig(final String config,
- final ServiceReference<?> serviceReference) {
+ static AuthenticationRequirementHolder fromConfig(final String config, final ServiceReference<?> serviceReference) {
if (config == null || config.length() == 0) {
- throw new IllegalArgumentException(
- "Configuration must not be null or empty");
+ throw new IllegalArgumentException("Configuration must not be null or empty");
}
final boolean required;
@@ -44,13 +42,11 @@ class AuthenticationRequirementHolder extends PathBasedHolder {
path = config;
}
- return new AuthenticationRequirementHolder(path, required,
- serviceReference);
+ return new AuthenticationRequirementHolder(path, required, serviceReference);
}
- AuthenticationRequirementHolder(final String fullPath,
- final boolean requiresAuthentication,
- final ServiceReference<?> serviceReference) {
+ AuthenticationRequirementHolder(
+ final String fullPath, final boolean requiresAuthentication, final ServiceReference<?> serviceReference) {
super(fullPath, serviceReference);
this.requiresAuthentication = requiresAuthentication;
}
@@ -69,14 +65,10 @@ class AuthenticationRequirementHolder extends PathBasedHolder {
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
+ if (getClass() != obj.getClass()) return false;
AuthenticationRequirementHolder other = (AuthenticationRequirementHolder) obj;
return requiresAuthentication == other.requiresAuthentication;
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManager.java b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManager.java
index 2d84fab..28fd3e4 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManager.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManager.java
@@ -59,17 +59,16 @@ import org.slf4j.LoggerFactory;
* the service registry.
*
*/
-@Component(service = {AuthenticationRequirementsManager.class, EventHandler.class},
- configurationPid = SlingAuthenticator.PID,
- property = {
- EventConstants.EVENT_TOPIC + "=" + SlingConstants.TOPIC_RESOURCE_RESOLVER_MAPPING_CHANGED
- })
-public class AuthenticationRequirementsManager
- extends PathBasedHolderCache<AuthenticationRequirementHolder>
- implements AllServiceListener, EventHandler {
+@Component(
+ service = {AuthenticationRequirementsManager.class, EventHandler.class},
+ configurationPid = SlingAuthenticator.PID,
+ property = {EventConstants.EVENT_TOPIC + "=" + SlingConstants.TOPIC_RESOURCE_RESOLVER_MAPPING_CHANGED})
+public class AuthenticationRequirementsManager extends PathBasedHolderCache<AuthenticationRequirementHolder>
+ implements AllServiceListener, EventHandler {
/** Filter expression for auth requirements */
- private static final String FILTER_EXPR = "(".concat(AuthConstants.AUTH_REQUIREMENTS).concat("=*)");
+ private static final String FILTER_EXPR =
+ "(".concat(AuthConstants.AUTH_REQUIREMENTS).concat("=*)");
/** Fake service id to indicate an update of a mapping */
private static final Long UPDATE = 0L;
@@ -107,7 +106,8 @@ public class AuthenticationRequirementsManager
* @param factory The resource resolver factory
*/
@Activate
- public AuthenticationRequirementsManager(final BundleContext context,
+ public AuthenticationRequirementsManager(
+ final BundleContext context,
@Reference ResourceResolverFactory factory,
final SlingAuthenticator.Config config) {
this(context, factory, config, Executors.newSingleThreadExecutor());
@@ -133,8 +133,8 @@ public class AuthenticationRequirementsManager
if (refs != null) {
for (final ServiceReference<?> ref : refs) {
final Bundle bundle = ref.getBundle();
- if ( bundle != null && bundle.getBundleId() != this.bundleId ) {
- final Long id = (Long)ref.getProperty(Constants.SERVICE_ID);
+ if (bundle != null && bundle.getBundleId() != this.bundleId) {
+ final Long id = (Long) ref.getProperty(Constants.SERVICE_ID);
this.queue(id, new Action(ActionType.ADDED, ref));
}
}
@@ -152,23 +152,20 @@ public class AuthenticationRequirementsManager
private void modified(final SlingAuthenticator.Config config) {
this.clear();
this.addHolder(new AuthenticationRequirementHolder("/", !config.auth_annonymous(), null));
-
+
if (config.sling_auth_requirements() != null) {
for (String authReq : config.sling_auth_requirements()) {
if (authReq != null && authReq.length() > 0) {
- this.addHolder(AuthenticationRequirementHolder.fromConfig(
- authReq, null));
+ this.addHolder(AuthenticationRequirementHolder.fromConfig(authReq, null));
} else {
logger.warn("Ignoring null/empty config for auth requirements");
}
}
}
// don't require authentication for login/logout servlets
- this.addHolder(new AuthenticationRequirementHolder(
- LoginServlet.SERVLET_PATH, false, null));
- this.addHolder(new AuthenticationRequirementHolder(
- LogoutServlet.SERVLET_PATH, false, null));
-
+ this.addHolder(new AuthenticationRequirementHolder(LoginServlet.SERVLET_PATH, false, null));
+ this.addHolder(new AuthenticationRequirementHolder(LogoutServlet.SERVLET_PATH, false, null));
+
// add all registered services
this.registerAllServices();
}
@@ -184,7 +181,7 @@ public class AuthenticationRequirementsManager
}
private void schedule() {
- if ( this.backgroundJobRunning.compareAndSet(false, true) ) {
+ if (this.backgroundJobRunning.compareAndSet(false, true)) {
this.executor.execute(this::processQueue);
}
}
@@ -195,25 +192,25 @@ public class AuthenticationRequirementsManager
@Override
public void serviceChanged(final ServiceEvent event) {
final Bundle bundle = event.getServiceReference().getBundle();
- if ( bundle != null && bundle.getBundleId() == this.bundleId ) {
+ if (bundle != null && bundle.getBundleId() == this.bundleId) {
// ignore all services from this bundle
return;
}
// modification of service properties, unregistration of the
// service or service properties does not contain requirements
// property any longer (new event with type 8 added in OSGi Core 4.2)
- final Long id = (Long)event.getServiceReference().getProperty(Constants.SERVICE_ID);
+ final Long id = (Long) event.getServiceReference().getProperty(Constants.SERVICE_ID);
if ((event.getType() & (ServiceEvent.UNREGISTERING | ServiceEvent.MODIFIED_ENDMATCH)) != 0) {
queue(id, new Action(ActionType.REMOVED, event.getServiceReference()));
}
- if ((event.getType() & ServiceEvent.MODIFIED ) != 0) {
+ if ((event.getType() & ServiceEvent.MODIFIED) != 0) {
queue(id, new Action(ActionType.MODIFIED, event.getServiceReference()));
}
// add requirements for newly registered services and for
// updated services
- if ((event.getType() & ServiceEvent.REGISTERED ) != 0) {
+ if ((event.getType() & ServiceEvent.REGISTERED) != 0) {
queue(id, new Action(ActionType.ADDED, event.getServiceReference()));
}
schedule();
@@ -235,11 +232,11 @@ public class AuthenticationRequirementsManager
*/
private void queue(final long id, final Action action) {
logger.debug("Queuing action for service {} : {}", id, action);
- synchronized ( this.processingQueue ) {
- if ( id == CLEAR ) {
+ synchronized (this.processingQueue) {
+ if (id == CLEAR) {
this.processingQueue.clear();
- } else if ( id == UPDATE ) {
- for(final Long updateId: this.props.keySet()) {
+ } else if (id == UPDATE) {
+ for (final Long updateId : this.props.keySet()) {
this.processingQueue.putIfAbsent(updateId, new Action(ActionType.UPDATE, null));
}
} else {
@@ -257,26 +254,27 @@ public class AuthenticationRequirementsManager
ResourceResolver resolver = null;
ResourceMapper mapper = null;
try {
- while ( this.backgroundJobRunning.get() ) {
+ while (this.backgroundJobRunning.get()) {
Map.Entry<Long, Action> entry = null;
- synchronized ( this.processingQueue ) {
- final Iterator<Map.Entry<Long, Action> > iter = this.processingQueue.entrySet().iterator();
- if ( iter.hasNext() ) {
+ synchronized (this.processingQueue) {
+ final Iterator<Map.Entry<Long, Action>> iter =
+ this.processingQueue.entrySet().iterator();
+ if (iter.hasNext()) {
entry = iter.next();
iter.remove();
}
}
- if ( entry == null ) {
- synchronized ( this.processingQueue ) {
+ if (entry == null) {
+ synchronized (this.processingQueue) {
this.backgroundJobRunning.compareAndSet(true, !this.processingQueue.isEmpty());
}
} else {
logger.debug("Processing action for service {} : {}", entry.getKey(), entry.getValue());
- if ( entry.getValue().type != ActionType.REMOVED && mapper == null ) {
+ if (entry.getValue().type != ActionType.REMOVED && mapper == null) {
try {
resolver = this.resolverFactory.getServiceResourceResolver(null);
mapper = resolver.adaptTo(ResourceMapper.class);
- } catch ( final org.apache.sling.api.resource.LoginException le) {
+ } catch (final org.apache.sling.api.resource.LoginException le) {
// ignore
}
}
@@ -285,7 +283,7 @@ public class AuthenticationRequirementsManager
}
} finally {
- if ( resolver != null ) {
+ if (resolver != null) {
resolver.close();
}
}
@@ -298,17 +296,21 @@ public class AuthenticationRequirementsManager
* @param action
*/
private void process(final ResourceMapper mapper, final Long id, final Action action) {
- switch ( action.type ) {
- case ADDED : this.addService(mapper, action.reference);
- break;
- case REMOVED : this.removeService((Long)action.reference.getProperty(Constants.SERVICE_ID));
- break;
- case MODIFIED : this.modifiedService(mapper, action.reference);
- break;
- case UPDATE: final List<AuthenticationRequirementHolder> list = props.get(id);
- if (!list.isEmpty() ) {
- this.modifiedService(mapper, list.get(0).serviceReference);
- }
+ switch (action.type) {
+ case ADDED:
+ this.addService(mapper, action.reference);
+ break;
+ case REMOVED:
+ this.removeService((Long) action.reference.getProperty(Constants.SERVICE_ID));
+ break;
+ case MODIFIED:
+ this.modifiedService(mapper, action.reference);
+ break;
+ case UPDATE:
+ final List<AuthenticationRequirementHolder> list = props.get(id);
+ if (!list.isEmpty()) {
+ this.modifiedService(mapper, list.get(0).serviceReference);
+ }
}
}
@@ -316,7 +318,7 @@ public class AuthenticationRequirementsManager
* Register all known services.
*/
void registerAllServices() {
- for(final List<AuthenticationRequirementHolder> authReqs : props.values()) {
+ for (final List<AuthenticationRequirementHolder> authReqs : props.values()) {
registerService(authReqs);
}
}
@@ -333,15 +335,15 @@ public class AuthenticationRequirementsManager
private Set<String> buildPathsSet(final ResourceMapper mapper, final String[] authReqPaths) {
final Set<String> paths = new HashSet<>();
- for(String authReq : authReqPaths) {
- if (authReq != null ) {
+ for (String authReq : authReqPaths) {
+ if (authReq != null) {
authReq = authReq.trim();
- if ( authReq.length() > 0 ) {
+ if (authReq.length() > 0) {
final String prefix;
- if ( authReq.startsWith("+") ) {
+ if (authReq.startsWith("+")) {
prefix = null;
authReq = authReq.substring(1);
- } else if ( authReq.startsWith("-") ) {
+ } else if (authReq.startsWith("-")) {
prefix = "-";
authReq = authReq.substring(1);
} else {
@@ -349,8 +351,8 @@ public class AuthenticationRequirementsManager
}
paths.add(prefix == null ? authReq : prefix.concat(authReq));
- if ( mapper != null ) {
- for(final String mappedPath : mapper.getAllMappings(authReq)) {
+ if (mapper != null) {
+ for (final String mappedPath : mapper.getAllMappings(authReq)) {
paths.add(prefix == null ? mappedPath : prefix.concat(mappedPath));
}
}
@@ -365,14 +367,16 @@ public class AuthenticationRequirementsManager
* @param ref The service reference
*/
private void addService(final ResourceMapper mapper, final ServiceReference<?> ref) {
- final String[] authReqPaths = Converters.standardConverter().convert(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS)).to(String[].class);
- if ( authReqPaths.length > 0 ) {
- final Long id = (Long)ref.getProperty(Constants.SERVICE_ID);
+ final String[] authReqPaths = Converters.standardConverter()
+ .convert(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS))
+ .to(String[].class);
+ if (authReqPaths.length > 0) {
+ final Long id = (Long) ref.getProperty(Constants.SERVICE_ID);
final Set<String> paths = buildPathsSet(mapper, authReqPaths);
- if ( !paths.isEmpty() ) {
+ if (!paths.isEmpty()) {
final List<AuthenticationRequirementHolder> authReqList = new ArrayList<>();
- for(final String authReq : paths) {
+ for (final String authReq : paths) {
if (authReq == null || authReq.isEmpty()) {
logger.warn("Ignoring null/empty path while adding auth requirements for service {}", id);
continue;
@@ -394,35 +398,40 @@ public class AuthenticationRequirementsManager
* @param ref The service reference
*/
private void modifiedService(final ResourceMapper mapper, final ServiceReference<?> ref) {
- final String[] authReqPaths = Converters.standardConverter().convert(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS)).to(String[].class);
- final Long id = (Long)ref.getProperty(Constants.SERVICE_ID);
- if ( authReqPaths.length > 0 ) {
+ final String[] authReqPaths = Converters.standardConverter()
+ .convert(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS))
+ .to(String[].class);
+ final Long id = (Long) ref.getProperty(Constants.SERVICE_ID);
+ if (authReqPaths.length > 0) {
final Set<String> oldPaths = regProps.get(id);
- if ( oldPaths == null ) {
+ if (oldPaths == null) {
addService(mapper, ref);
} else {
final Set<String> paths = buildPathsSet(mapper, authReqPaths);
- if ( paths.isEmpty() ) {
+ if (paths.isEmpty()) {
removeService(id);
} else {
final List<AuthenticationRequirementHolder> authReqs = props.get(id);
// compare sets
- for(final String oldPath : oldPaths) {
+ for (final String oldPath : oldPaths) {
if (oldPath == null || oldPath.isEmpty()) {
continue;
- } else if ( !paths.contains(oldPath) ) {
+ } else if (!paths.contains(oldPath)) {
// remove
- final AuthenticationRequirementHolder holder = AuthenticationRequirementHolder.fromConfig(oldPath, ref);
+ final AuthenticationRequirementHolder holder =
+ AuthenticationRequirementHolder.fromConfig(oldPath, ref);
authReqs.remove(holder);
this.removeHolder(holder);
}
}
- for(final String path : paths) {
+ for (final String path : paths) {
if (path == null || path.isEmpty()) {
- logger.warn("Ignoring null/empty path while updating the auth requirements for service {}", id);
- } else if ( !oldPaths.contains(path) ) {
+ logger.warn(
+ "Ignoring null/empty path while updating the auth requirements for service {}", id);
+ } else if (!oldPaths.contains(path)) {
// add
- final AuthenticationRequirementHolder holder = AuthenticationRequirementHolder.fromConfig(path, ref);
+ final AuthenticationRequirementHolder holder =
+ AuthenticationRequirementHolder.fromConfig(path, ref);
authReqs.add(holder);
this.addHolder(holder);
}
@@ -456,7 +465,10 @@ public class AuthenticationRequirementsManager
*
*/
public enum ActionType {
- ADDED, MODIFIED, REMOVED, UPDATE
+ ADDED,
+ MODIFIED,
+ REMOVED,
+ UPDATE
}
/**
diff --git a/src/main/java/org/apache/sling/auth/core/impl/AuthenticatorWebConsolePlugin.java b/src/main/java/org/apache/sling/auth/core/impl/AuthenticatorWebConsolePlugin.java
index 1ab9ef8..bfc5444 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/AuthenticatorWebConsolePlugin.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/AuthenticatorWebConsolePlugin.java
@@ -28,7 +28,6 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.request.ResponseUtil;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
@@ -38,13 +37,14 @@ import org.osgi.service.component.propertytypes.ServiceDescription;
import org.osgi.service.component.propertytypes.ServiceVendor;
@SuppressWarnings("serial")
-@Component(service = Servlet.class,
- configurationPid = SlingAuthenticator.PID,
- property = {
+@Component(
+ service = Servlet.class,
+ configurationPid = SlingAuthenticator.PID,
+ property = {
"felix.webconsole.label=" + AuthenticatorWebConsolePlugin.LABEL,
"felix.webconsole.title=" + AuthenticatorWebConsolePlugin.TITLE,
"felix.webconsole.category=Sling"
- })
+ })
@ServiceDescription("Apache Sling Request Authenticator WebConsole Plugin")
@ServiceVendor("The Apache Software Foundation")
public class AuthenticatorWebConsolePlugin extends HttpServlet {
@@ -73,8 +73,7 @@ public class AuthenticatorWebConsolePlugin extends HttpServlet {
}
@Override
- protected void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// only handle GET requests, ensure no error message for other requests
if ("GET".equals(req.getMethod()) || "HEAD".equals(req.getMethod())) {
super.service(req, resp);
@@ -82,8 +81,7 @@ public class AuthenticatorWebConsolePlugin extends HttpServlet {
}
@Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
PrintWriter pw = resp.getWriter();
@@ -149,12 +147,14 @@ public class AuthenticatorWebConsolePlugin extends HttpServlet {
td(pw, (req.requiresAuthentication() ? "Yes" : "No"));
td(pw, req.getProvider());
endTr(pw);
-
}
}
private void printAuthenticationConfiguration(final PrintWriter pw) {
- final String anonUser = (this.config.sling_auth_anonymous_user() != null && this.config.sling_auth_anonymous_user().isEmpty()) ? this.config.sling_auth_anonymous_user() : "(default)";
+ final String anonUser = (this.config.sling_auth_anonymous_user() != null
+ && this.config.sling_auth_anonymous_user().isEmpty())
+ ? this.config.sling_auth_anonymous_user()
+ : "(default)";
final String sudoCookie = this.config.auth_sudo_cookie();
final String sudoParam = this.config.auth_sudo_parameter();
@@ -179,6 +179,7 @@ public class AuthenticatorWebConsolePlugin extends HttpServlet {
private void td(final PrintWriter pw, String content) {
td(pw, content, -1);
}
+
private void td(final PrintWriter pw, String content, int colspan) {
if (colspan > 1) {
pw.printf("<td class='content' colspan='%d'>%s</td>%n", colspan, ResponseUtil.escapeXml(content));
@@ -194,5 +195,4 @@ public class AuthenticatorWebConsolePlugin extends HttpServlet {
private void endTr(final PrintWriter pw) {
pw.println("</tr>");
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/FailureCodesMapper.java b/src/main/java/org/apache/sling/auth/core/impl/FailureCodesMapper.java
index f3699b6..6e864aa 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/FailureCodesMapper.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/FailureCodesMapper.java
@@ -46,7 +46,8 @@ public final class FailureCodesMapper {
// force failure attribute to be set so handlers can
// react to this special circumstance
Object creds = authInfo.get("user.jcr.credentials");
- if (creds instanceof SimpleCredentials && ((SimpleCredentials) creds).getAttribute("PasswordHistoryException") != null) {
+ if (creds instanceof SimpleCredentials
+ && ((SimpleCredentials) creds).getAttribute("PasswordHistoryException") != null) {
code = FAILURE_REASON_CODES.PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY;
} else {
code = FAILURE_REASON_CODES.PASSWORD_EXPIRED;
diff --git a/src/main/java/org/apache/sling/auth/core/impl/HttpBasicAuthenticationHandler.java b/src/main/java/org/apache/sling/auth/core/impl/HttpBasicAuthenticationHandler.java
index 1152301..bd07b73 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/HttpBasicAuthenticationHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/HttpBasicAuthenticationHandler.java
@@ -23,7 +23,6 @@ import java.nio.charset.StandardCharsets;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.commons.codec.binary.Base64;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
@@ -45,8 +44,8 @@ import org.slf4j.LoggerFactory;
* an easy way for tools (like cURL) or libraries (like Apache HttpCLient) to
* preemptively authenticate with HTTP Basic authentication.
*/
-class HttpBasicAuthenticationHandler extends
- DefaultJakartaAuthenticationFeedbackHandler implements JakartaAuthenticationHandler {
+class HttpBasicAuthenticationHandler extends DefaultJakartaAuthenticationFeedbackHandler
+ implements JakartaAuthenticationHandler {
private static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
@@ -69,8 +68,7 @@ class HttpBasicAuthenticationHandler extends
*/
private final boolean fullSupport;
- HttpBasicAuthenticationHandler(final String realm,
- final boolean fullSupport) {
+ HttpBasicAuthenticationHandler(final String realm, final boolean fullSupport) {
this.realm = realm;
this.fullSupport = fullSupport;
}
@@ -98,8 +96,7 @@ class HttpBasicAuthenticationHandler extends
* information. In case of DOING_AUTH, the method has sent back a
* 401 requesting the client to provide credentials.
*/
- public AuthenticationInfo extractCredentials(HttpServletRequest request,
- HttpServletResponse response) {
+ public AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response) {
// extract credentials and return
AuthenticationInfo info = this.extractCredentials(request);
@@ -131,8 +128,7 @@ class HttpBasicAuthenticationHandler extends
* could be sent. If full support is not enabled <code>false</code>
* is always returned.
*/
- public boolean requestCredentials(HttpServletRequest request,
- HttpServletResponse response) {
+ public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) {
return fullSupport && sendUnauthorized(response);
}
@@ -148,8 +144,7 @@ class HttpBasicAuthenticationHandler extends
* nasty side-effect is that the browser's login form is displayed as a
* reaction to the 401/UNAUTHORIZED response.
*/
- public void dropCredentials(HttpServletRequest request,
- HttpServletResponse response) {
+ public void dropCredentials(HttpServletRequest request, HttpServletResponse response) {
if (fullSupport && request.getHeader(HEADER_AUTHORIZATION) != null) {
sendUnauthorized(response);
}
@@ -176,8 +171,8 @@ class HttpBasicAuthenticationHandler extends
* response to be sent.
*/
@Override
- public void authenticationFailed(HttpServletRequest request, HttpServletResponse response,
- AuthenticationInfo authInfo) {
+ public void authenticationFailed(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
if (!AuthUtil.isValidateRequest(request)) {
sendUnauthorized(response);
}
@@ -219,8 +214,7 @@ class HttpBasicAuthenticationHandler extends
* @return <code>true</code> if the 401/UNAUTHORIZED method has successfully
* been sent.
*/
- private boolean forceAuthentication(HttpServletRequest request,
- HttpServletResponse response) {
+ private boolean forceAuthentication(HttpServletRequest request, HttpServletResponse response) {
// presume 401/UNAUTHORIZED has not been sent
boolean authenticationForced = false;
@@ -232,9 +226,8 @@ class HttpBasicAuthenticationHandler extends
} else {
log.debug(
- "forceAuthentication: Not forcing authentication because request parameter {} is not set",
- REQUEST_LOGIN_PARAMETER);
-
+ "forceAuthentication: Not forcing authentication because request parameter {} is not set",
+ REQUEST_LOGIN_PARAMETER);
}
// true if 401/UNAUTHORIZED has been sent, false otherwise
@@ -276,15 +269,13 @@ class HttpBasicAuthenticationHandler extends
// error handler in which case sendError would result in an error
// handler loop and thus be ignored.
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- response.setHeader(HEADER_WWW_AUTHENTICATE,
- AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\"");
+ response.setHeader(HEADER_WWW_AUTHENTICATE, AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\"");
try {
response.flushBuffer();
return true;
} catch (IOException ioe) {
- log.error("sendUnauthorized: Failed requesting authentication",
- ioe);
+ log.error("sendUnauthorized: Failed requesting authentication", ioe);
}
}
@@ -293,8 +284,7 @@ class HttpBasicAuthenticationHandler extends
@Override
public String toString() {
- return "HTTP Basic Authentication Handler ("
- + (fullSupport ? "enabled" : "preemptive") + ")";
+ return "HTTP Basic Authentication Handler (" + (fullSupport ? "enabled" : "preemptive") + ")";
}
// ---------- internal -----------------------------------------------------
@@ -344,7 +334,6 @@ class HttpBasicAuthenticationHandler extends
password = decoded.substring(colIdx + 1).toCharArray();
}
- return new AuthenticationInfo(HttpServletRequest.BASIC_AUTH, userId,
- password);
+ return new AuthenticationInfo(HttpServletRequest.BASIC_AUTH, userId, password);
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/LoginServlet.java b/src/main/java/org/apache/sling/auth/core/impl/LoginServlet.java
index 175d185..a765042 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/LoginServlet.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/LoginServlet.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.auth.core.impl;
-import java.io.IOException;
-
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.auth.Authenticator;
@@ -41,12 +41,13 @@ import org.slf4j.LoggerFactory;
/**
* The <code>LoginServlet</code> lets the Authenticator do the login.
*/
-@Component(service = Servlet.class,
- property = {
- "sling.servlet.methods=GET",
- "sling.servlet.methods=POST",
- "sling.servlet.paths=" + LoginServlet.SERVLET_PATH
- })
+@Component(
+ service = Servlet.class,
+ property = {
+ "sling.servlet.methods=GET",
+ "sling.servlet.methods=POST",
+ "sling.servlet.paths=" + LoginServlet.SERVLET_PATH
+ })
@ServiceDescription("Authenticator Login Servlet")
@ServiceVendor("The Apache Software Foundation")
public class LoginServlet extends SlingAllMethodsServlet {
@@ -67,9 +68,7 @@ public class LoginServlet extends SlingAllMethodsServlet {
public static final String SERVLET_PATH = "/system/sling/login"; // NOSONAR
@Override
- protected void service(SlingHttpServletRequest request,
- SlingHttpServletResponse response) throws IOException {
-
+ protected void service(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
// if the request is logged in and the resource is not set (such
// as when requesting /system/sling/login from the browser with the
@@ -81,9 +80,7 @@ public class LoginServlet extends SlingAllMethodsServlet {
final String resourcePath = AuthUtil.getLoginResource(request, null);
if (isSelf(resourcePath)) {
String redirectTarget = request.getContextPath() + "/";
- log.warn(
- "doGet: Redirecting to {} to prevent login loop for resource",
- redirectTarget);
+ log.warn("doGet: Redirecting to {} to prevent login loop for resource", redirectTarget);
response.sendRedirect(redirectTarget);
return;
}
@@ -106,13 +103,11 @@ public class LoginServlet extends SlingAllMethodsServlet {
} catch (NoAuthenticationHandlerException nahe) {
log.error("doGet: No AuthenticationHandler to login registered");
-
}
} else {
log.error("doGet: Authenticator service missing, cannot login");
-
}
// fall back to forbid access
diff --git a/src/main/java/org/apache/sling/auth/core/impl/LogoutServlet.java b/src/main/java/org/apache/sling/auth/core/impl/LogoutServlet.java
index c61c0b8..2278e5a 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/LogoutServlet.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/LogoutServlet.java
@@ -42,16 +42,16 @@ import org.slf4j.LoggerFactory;
* The <code>LogoutServlet</code> lets the Authenticator
* do the logout.
*/
-@Component(service = Servlet.class,
- property = {
- "sling.servlet.paths=" + LogoutServlet.SERVLET_PATH
- })
+@Component(
+ service = Servlet.class,
+ property = {"sling.servlet.paths=" + LogoutServlet.SERVLET_PATH})
@ServiceDescription("Authenticator Logout Servlet")
@ServiceVendor("The Apache Software Foundation")
@Designate(ocd = LogoutServlet.Config.class)
public class LogoutServlet extends SlingAllMethodsServlet {
- @ObjectClassDefinition(name = "Apache Sling Authentication Logout Servlet",
+ @ObjectClassDefinition(
+ name = "Apache Sling Authentication Logout Servlet",
description = "Servlet for logging out users through the authenticator service.")
public @interface Config {
@@ -74,8 +74,7 @@ public class LogoutServlet extends SlingAllMethodsServlet {
public static final String SERVLET_PATH = "/system/sling/logout"; // NOSONAR
@Override
- protected void service(SlingHttpServletRequest request,
- SlingHttpServletResponse response) {
+ protected void service(SlingHttpServletRequest request, SlingHttpServletResponse response) {
final Authenticator authenticatorRef = this.authenticator;
if (authenticatorRef != null) {
diff --git a/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolder.java b/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolder.java
index af04f1e..c85b16d 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolder.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolder.java
@@ -83,8 +83,7 @@ public abstract class PathBasedHolder implements Comparable<PathBasedHolder> {
* @param serviceReference The reference to the service providing the
* configuration for this instance.
*/
- protected PathBasedHolder(final String url,
- final ServiceReference<?> serviceReference) {
+ protected PathBasedHolder(final String url, final ServiceReference<?> serviceReference) {
String newPath = url;
String newHost = "";
@@ -135,12 +134,17 @@ public abstract class PathBasedHolder implements Comparable<PathBasedHolder> {
return "Apache Sling Request Authenticator";
}
- final String descr = Converters.standardConverter().convert(serviceReference.getProperty(Constants.SERVICE_DESCRIPTION)).to(String.class);
+ final String descr = Converters.standardConverter()
+ .convert(serviceReference.getProperty(Constants.SERVICE_DESCRIPTION))
+ .to(String.class);
if (descr != null) {
return descr;
}
- final String id = Converters.standardConverter().convert(serviceReference.getProperty(Constants.SERVICE_ID)).defaultValue("unknown").to(String.class);
+ final String id = Converters.standardConverter()
+ .convert(serviceReference.getProperty(Constants.SERVICE_ID))
+ .defaultValue("unknown")
+ .to(String.class);
return "Service ".concat(id);
}
@@ -163,9 +167,10 @@ public abstract class PathBasedHolder implements Comparable<PathBasedHolder> {
return true;
}
- return path.startsWith(this.path) && (path.charAt(holderPathLength) == '/' || path.charAt(holderPathLength) == '.');
+ return path.startsWith(this.path)
+ && (path.charAt(holderPathLength) == '/' || path.charAt(holderPathLength) == '.');
}
-
+
/**
* Compares this instance to the <code>other</code> PathBasedHolder
* instance. Comparison takes into account the {@link #path} first. If they
@@ -196,7 +201,7 @@ public abstract class PathBasedHolder implements Comparable<PathBasedHolder> {
// now compare the service references giving priority to
// to the higher priority service
if (serviceReference == null) {
- if ( other.serviceReference == null ) {
+ if (other.serviceReference == null) {
return this.getClass().getName().compareTo(other.getClass().getName());
}
return -1;
@@ -205,7 +210,7 @@ public abstract class PathBasedHolder implements Comparable<PathBasedHolder> {
}
final int serviceResult = other.serviceReference.compareTo(serviceReference);
- if ( serviceResult != 0 ) {
+ if (serviceResult != 0) {
return serviceResult;
}
return this.getClass().getName().compareTo(other.getClass().getName());
@@ -235,7 +240,8 @@ public abstract class PathBasedHolder implements Comparable<PathBasedHolder> {
if (obj.getClass() == getClass()) {
PathBasedHolder other = (PathBasedHolder) obj;
return fullPath.equals(other.fullPath)
- && ((serviceReference == null && other.serviceReference == null) || (serviceReference != null && serviceReference.equals(other.serviceReference)));
+ && ((serviceReference == null && other.serviceReference == null)
+ || (serviceReference != null && serviceReference.equals(other.serviceReference)));
}
return false;
diff --git a/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolderCache.java b/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolderCache.java
index 197f63e..7e5f9da 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolderCache.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/PathBasedHolderCache.java
@@ -42,7 +42,8 @@ public class PathBasedHolderCache<T extends PathBasedHolder> {
}
public synchronized void addHolder(final T holder) {
- final Map<String, SortedSet<T>> byHostMap = cache.computeIfAbsent(holder.protocol, protocol -> new ConcurrentHashMap<>());
+ final Map<String, SortedSet<T>> byHostMap =
+ cache.computeIfAbsent(holder.protocol, protocol -> new ConcurrentHashMap<>());
// preset with current list
final SortedSet<T> currentPathSet = byHostMap.get(holder.host);
@@ -81,7 +82,7 @@ public class PathBasedHolderCache<T extends PathBasedHolder> {
public Collection<T>[] findApplicableHolders(final HttpServletRequest request) {
final String hostname;
- if ( request.getServerPort() != 80 && request.getServerPort() != 443 ) {
+ if (request.getServerPort() != 80 && request.getServerPort() != 443) {
hostname = request.getServerName().concat(":").concat(String.valueOf(request.getServerPort()));
} else {
hostname = request.getServerName();
@@ -91,12 +92,12 @@ public class PathBasedHolderCache<T extends PathBasedHolder> {
final SortedSet<T>[] result = new SortedSet[4];
final Map<String, SortedSet<T>> byHostMap = cache.get(request.getScheme());
- if ( byHostMap != null ) {
+ if (byHostMap != null) {
result[0] = byHostMap.get(hostname);
result[1] = byHostMap.get("");
}
final Map<String, SortedSet<T>> defaultByHostMap = cache.get("");
- if ( defaultByHostMap != null ) {
+ if (defaultByHostMap != null) {
result[2] = defaultByHostMap.get(hostname);
result[3] = defaultByHostMap.get("");
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetrics.java b/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetrics.java
index 1f6619f..d998c37 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetrics.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetrics.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl;
@@ -56,4 +58,4 @@ public class SlingAuthenticationMetrics {
authenticateFailed.mark();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticator.java b/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticator.java
index 1eb75d8..86626f2 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticator.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticator.java
@@ -36,7 +36,6 @@ import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.auth.Authenticator;
import org.apache.sling.api.auth.NoAuthenticationHandlerException;
@@ -98,115 +97,126 @@ import org.slf4j.LoggerFactory;
* Currently this class does not support multiple handlers for any one request
* URL.
*/
-@Component(name = SlingAuthenticator.PID,
- service = {Authenticator.class, AuthenticationSupport.class, ServletRequestListener.class})
+@Component(
+ name = SlingAuthenticator.PID,
+ service = {Authenticator.class, AuthenticationSupport.class, ServletRequestListener.class})
@HttpWhiteboardContextSelect("(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=*)")
@HttpWhiteboardListener
@ServiceDescription("Apache Sling Request Authenticator")
@ServiceVendor("The Apache Software Foundation")
@Designate(ocd = SlingAuthenticator.Config.class)
-public class SlingAuthenticator implements Authenticator,
- AuthenticationSupport, ServletRequestListener {
+public class SlingAuthenticator implements Authenticator, AuthenticationSupport, ServletRequestListener {
/** The pid for the configuration */
public static final String PID = "org.apache.sling.engine.impl.auth.SlingAuthenticator";
- @ObjectClassDefinition(name = "Apache Sling Authentication Service",
- description = "Extracts user authentication details from the request with" +
- " the help of authentication handlers registered as separate services. One" +
- " example of such an authentication handler is the handler HTTP Authorization" +
- " header contained authentication.")
+ @ObjectClassDefinition(
+ name = "Apache Sling Authentication Service",
+ description = "Extracts user authentication details from the request with"
+ + " the help of authentication handlers registered as separate services. One"
+ + " example of such an authentication handler is the handler HTTP Authorization"
+ + " header contained authentication.")
public @interface Config {
- @AttributeDefinition(name = "Impersonation Cookie",
- description = "The name the HTTP Cookie to set with the value" +
- " of the user which is to be impersonated. This cookie will always be a session" +
- " cookie.")
+ @AttributeDefinition(
+ name = "Impersonation Cookie",
+ description = "The name the HTTP Cookie to set with the value"
+ + " of the user which is to be impersonated. This cookie will always be a session"
+ + " cookie.")
String auth_sudo_cookie() default "sling.sudo"; // NOSONAR
- @AttributeDefinition(name = "Impersonation Parameter",
- description = "The name of the request parameter initiating" +
- " impersonation. Setting this parameter to a user id will result in using an" +
- " impersonated session (instead of the actually authenticated session) and set" +
- " a session cookie of the name defined in the Impersonation Cookie setting.")
+ @AttributeDefinition(
+ name = "Impersonation Parameter",
+ description = "The name of the request parameter initiating"
+ + " impersonation. Setting this parameter to a user id will result in using an"
+ + " impersonated session (instead of the actually authenticated session) and set"
+ + " a session cookie of the name defined in the Impersonation Cookie setting.")
String auth_sudo_parameter() default "sudo"; // NOSONAR
- @AttributeDefinition(name = "Allow Anonymous Access",
- description = "Whether default access as anonymous when no" +
- " credentials are present in the request is allowed. The default value is" +
- " \"true\" to allow access without credentials. When set to \"false\" access to the" +
- " repository is only allowed if valid credentials are presented. The value of" +
- " this configuration option is added to list of Authentication Requirements" +
- " and needs not be explicitly listed. If anonymous access is allowed the entry" +
- " added is \"-/\". Otherwise anonymous access is denied and \"+/\" is added to the" +
- " list.")
+ @AttributeDefinition(
+ name = "Allow Anonymous Access",
+ description = "Whether default access as anonymous when no"
+ + " credentials are present in the request is allowed. The default value is"
+ + " \"true\" to allow access without credentials. When set to \"false\" access to the"
+ + " repository is only allowed if valid credentials are presented. The value of"
+ + " this configuration option is added to list of Authentication Requirements"
+ + " and needs not be explicitly listed. If anonymous access is allowed the entry"
+ + " added is \"-/\". Otherwise anonymous access is denied and \"+/\" is added to the"
+ + " list.")
boolean auth_annonymous() default true; // NOSONAR
- @AttributeDefinition(name = "Authentication Requirements",
- description = "Defines URL space subtrees which require" +
- " or don't require authentication. For any request the best matching path" +
- " configured applies and defines whether authentication is actually required" +
- " for the request or not. Each entry in this list can be an absolute path (such" +
- " as /content) or and absolute URI (such as http://thehost/content). Optionally" +
- " each entry may be prefixed by a plus (+) or minus (-) sign indicating that" +
- " authentication is required (plus) or not required (minus). Example entries are" +
- " \"/content\" or \"+/content\" to require authentication at and below \"/content\" and" +
- " \"-/system/sling/login\" to not require authentication at and below" +
- " \"/system/sling/login\". By default this list is empty. This list is extended at" +
- " run time with additional entries: One entry is added for the \"Allow Anonymous" +
- " Access\" configuration. Other entries are added for any services setting the" +
- " \"sling.auth.requirements\" service registration property.")
+ @AttributeDefinition(
+ name = "Authentication Requirements",
+ description = "Defines URL space subtrees which require"
+ + " or don't require authentication. For any request the best matching path"
+ + " configured applies and defines whether authentication is actually required"
+ + " for the request or not. Each entry in this list can be an absolute path (such"
+ + " as /content) or and absolute URI (such as http://thehost/content). Optionally"
+ + " each entry may be prefixed by a plus (+) or minus (-) sign indicating that"
+ + " authentication is required (plus) or not required (minus). Example entries are"
+ + " \"/content\" or \"+/content\" to require authentication at and below \"/content\" and"
+ + " \"-/system/sling/login\" to not require authentication at and below"
+ + " \"/system/sling/login\". By default this list is empty. This list is extended at"
+ + " run time with additional entries: One entry is added for the \"Allow Anonymous"
+ + " Access\" configuration. Other entries are added for any services setting the"
+ + " \"sling.auth.requirements\" service registration property.")
String[] sling_auth_requirements(); // NOSONAR
- @AttributeDefinition(name = "Anonymous User Name",
- description = "Defines which user name to assume" +
- " for anonymous requests, that is requests not providing credentials" +
- " supported by any of the registered authentication handlers. If this" +
- " property is missing or empty, the default is assumed which depends on" +
- " the resource provider(s). Otherwise anonymous requests are handled with" +
- " this user name. If the configured user name does not exist or is not" +
- " allowed to access the resource data, anonymous requests may still be" +
- " blocked. If anonymous access is not allowed, this property is ignored.")
+ @AttributeDefinition(
+ name = "Anonymous User Name",
+ description = "Defines which user name to assume"
+ + " for anonymous requests, that is requests not providing credentials"
+ + " supported by any of the registered authentication handlers. If this"
+ + " property is missing or empty, the default is assumed which depends on"
+ + " the resource provider(s). Otherwise anonymous requests are handled with"
+ + " this user name. If the configured user name does not exist or is not"
+ + " allowed to access the resource data, anonymous requests may still be"
+ + " blocked. If anonymous access is not allowed, this property is ignored.")
String sling_auth_anonymous_user(); // NOSONAR
- @AttributeDefinition(name = "Anonymous User Password",
- description = "Password for the anonymous" +
- " user defined in the Anonymous User Name field. This property is only" +
- " used if a non-empty anonymous user name is configured. If this property" +
- " is not defined but a password is required, an empty password would be" +
- " assumed.", type = AttributeType.PASSWORD)
+ @AttributeDefinition(
+ name = "Anonymous User Password",
+ description = "Password for the anonymous"
+ + " user defined in the Anonymous User Name field. This property is only"
+ + " used if a non-empty anonymous user name is configured. If this property"
+ + " is not defined but a password is required, an empty password would be"
+ + " assumed.",
+ type = AttributeType.PASSWORD)
String sling_auth_anonymous_password(); // NOSONAR
- @AttributeDefinition(name = "HTTP Basic Authentication",
- description = "Level of support for HTTP Basic Authentication. Such" +
- " support can be provided in three levels: (1) no support at all, that is" +
- " disabled, (2) preemptive support, that is HTTP Basic Authentication is" +
- " supported if the authentication header is set in the request, (3) full" +
- " support. The default is preemptive support unless Anonymous Access is" +
- " not allowed. In this case HTTP Basic Authentication is always enabled" +
- " to ensure clients can authenticate at least with basic authentication.",
+ @AttributeDefinition(
+ name = "HTTP Basic Authentication",
+ description = "Level of support for HTTP Basic Authentication. Such"
+ + " support can be provided in three levels: (1) no support at all, that is"
+ + " disabled, (2) preemptive support, that is HTTP Basic Authentication is"
+ + " supported if the authentication header is set in the request, (3) full"
+ + " support. The default is preemptive support unless Anonymous Access is"
+ + " not allowed. In this case HTTP Basic Authentication is always enabled"
+ + " to ensure clients can authenticate at least with basic authentication.",
options = {
- @Option(label = "Enabled", value = HTTP_AUTH_ENABLED),
- @Option(label = "Enabled (Preemptive)", value = HTTP_AUTH_PREEMPTIVE),
- @Option(label = "Disabled", value = HTTP_AUTH_DISABLED)
+ @Option(label = "Enabled", value = HTTP_AUTH_ENABLED),
+ @Option(label = "Enabled (Preemptive)", value = HTTP_AUTH_PREEMPTIVE),
+ @Option(label = "Disabled", value = HTTP_AUTH_DISABLED)
})
String auth_http() default HTTP_AUTH_PREEMPTIVE; // NOSONAR
- @AttributeDefinition(name = "Realm",
- description = "HTTP BASIC authentication realm. This property" +
- " is only used if the HTTP Basic Authentication support is not disabled. The" +
- " default value is \"Sling (Development)\".")
+ @AttributeDefinition(
+ name = "Realm",
+ description = "HTTP BASIC authentication realm. This property"
+ + " is only used if the HTTP Basic Authentication support is not disabled. The"
+ + " default value is \"Sling (Development)\".")
String auth_http_realm() default "Sling (Development)"; // NOSONAR
- @AttributeDefinition(name = "Authentication URI Suffices",
- description = "A list of request URI suffixes intended to" +
- " be handled by Authentication Handlers. Any request whose request URI" +
- " ends with any one of the listed suffices is intended to be handled by" +
- " an Authentication Handler causing the request to either be rejected or" +
- " the client being redirected to another location and thus the request not" +
- " being further processed after the authentication phase. The default is" +
- " just \"/j_security_check\" which is the suffix defined by the Servlet API" +
- " specification used for FORM based authentication.")
+ @AttributeDefinition(
+ name = "Authentication URI Suffices",
+ description = "A list of request URI suffixes intended to"
+ + " be handled by Authentication Handlers. Any request whose request URI"
+ + " ends with any one of the listed suffices is intended to be handled by"
+ + " an Authentication Handler causing the request to either be rejected or"
+ + " the client being redirected to another location and thus the request not"
+ + " being further processed after the authentication phase. The default is"
+ + " just \"/j_security_check\" which is the suffix defined by the Servlet API"
+ + " specification used for FORM based authentication.")
String[] auth_uri_suffix() default DEFAULT_AUTH_URI_SUFFIX; // NOSONAR
}
@@ -304,23 +314,36 @@ public class SlingAuthenticator implements Authenticator,
/**
* JakartaAuthenticationInfoPostProcessor services
*/
- @Reference(cardinality = ReferenceCardinality.MULTIPLE, service = JakartaAuthenticationInfoPostProcessor.class, fieldOption = FieldOption.REPLACE)
- private volatile List<JakartaAuthenticationInfoPostProcessor> jakartaAuthInfoPostProcessors = Collections.emptyList(); // NOSONAR
+ @Reference(
+ cardinality = ReferenceCardinality.MULTIPLE,
+ service = JakartaAuthenticationInfoPostProcessor.class,
+ fieldOption = FieldOption.REPLACE)
+ private volatile List<JakartaAuthenticationInfoPostProcessor> jakartaAuthInfoPostProcessors =
+ Collections.emptyList(); // NOSONAR
/**
* AuthenticationInfoPostProcessor services
*/
@SuppressWarnings("deprecation")
- @Reference(cardinality = ReferenceCardinality.MULTIPLE, service = AuthenticationInfoPostProcessor.class, fieldOption = FieldOption.REPLACE)
+ @Reference(
+ cardinality = ReferenceCardinality.MULTIPLE,
+ service = AuthenticationInfoPostProcessor.class,
+ fieldOption = FieldOption.REPLACE)
private volatile List<AuthenticationInfoPostProcessor> authInfoPostProcessors = Collections.emptyList(); // NOSONAR
/**
* The event admin service.
*/
- @Reference(policy=ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY)
+ @Reference(
+ policy = ReferencePolicy.DYNAMIC,
+ cardinality = ReferenceCardinality.OPTIONAL,
+ policyOption = ReferencePolicyOption.GREEDY)
private volatile EventAdmin eventAdmin; // NOSONAR
- @Reference(policy=ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY)
+ @Reference(
+ policy = ReferencePolicy.DYNAMIC,
+ cardinality = ReferenceCardinality.OPTIONAL,
+ policyOption = ReferencePolicyOption.GREEDY)
private volatile SlingAuthenticationMetrics metricsService;
private final ResourceResolverFactory resourceResolverFactory;
@@ -328,22 +351,30 @@ public class SlingAuthenticator implements Authenticator,
/**
* LoginEventDecorator services
*/
- @Reference(cardinality = ReferenceCardinality.MULTIPLE, service = JakartaLoginEventDecorator.class, fieldOption = FieldOption.REPLACE)
+ @Reference(
+ cardinality = ReferenceCardinality.MULTIPLE,
+ service = JakartaLoginEventDecorator.class,
+ fieldOption = FieldOption.REPLACE)
private volatile List<JakartaLoginEventDecorator> jakartaLoginEventDecorators = new ArrayList<>(); // NOSONAR
/**
* LoginEventDecorator services
*/
@SuppressWarnings("deprecation")
- @Reference(cardinality = ReferenceCardinality.MULTIPLE, service = LoginEventDecorator.class, fieldOption = FieldOption.REPLACE)
+ @Reference(
+ cardinality = ReferenceCardinality.MULTIPLE,
+ service = LoginEventDecorator.class,
+ fieldOption = FieldOption.REPLACE)
private volatile List<LoginEventDecorator> loginEventDecorators = new ArrayList<>(); // NOSONAR
// ---------- SCR integration
@Activate
- public SlingAuthenticator(@Reference AuthenticationRequirementsManager authReqManager,
+ public SlingAuthenticator(
+ @Reference AuthenticationRequirementsManager authReqManager,
@Reference AuthenticationHandlersManager authHandlerManager,
- @Reference(policyOption = ReferencePolicyOption.GREEDY) final ResourceResolverFactory resourceResolverFactory,
+ @Reference(policyOption = ReferencePolicyOption.GREEDY)
+ final ResourceResolverFactory resourceResolverFactory,
final BundleContext bundleContext,
final Config config) {
this.resourceResolverFactory = resourceResolverFactory;
@@ -357,21 +388,26 @@ public class SlingAuthenticator implements Authenticator,
private void modified(final Config config) {
if (!config.auth_sudo_cookie().equals(this.sudoCookieName)) {
log.info(
- "modified: Setting new cookie name for impersonation {} (was {})",
- config.auth_sudo_cookie(), this.sudoCookieName);
+ "modified: Setting new cookie name for impersonation {} (was {})",
+ config.auth_sudo_cookie(),
+ this.sudoCookieName);
this.sudoCookieName = config.auth_sudo_cookie();
}
if (!config.auth_sudo_parameter().equals(this.sudoParameterName)) {
log.info(
- "modified: Setting new parameter name for impersonation {} (was {})",
- config.auth_sudo_parameter(), this.sudoParameterName);
+ "modified: Setting new parameter name for impersonation {} (was {})",
+ config.auth_sudo_parameter(),
+ this.sudoParameterName);
this.sudoParameterName = config.auth_sudo_parameter();
}
- if (config.sling_auth_anonymous_user() != null && config.sling_auth_anonymous_user().length() > 0) {
+ if (config.sling_auth_anonymous_user() != null
+ && config.sling_auth_anonymous_user().length() > 0) {
this.anonUser = config.sling_auth_anonymous_user();
- this.anonPassword = config.sling_auth_anonymous_password() == null ? "".toCharArray() : config.sling_auth_anonymous_password().toCharArray();
+ this.anonPassword = config.sling_auth_anonymous_password() == null
+ ? "".toCharArray()
+ : config.sling_auth_anonymous_password().toCharArray();
} else {
this.anonUser = null;
this.anonPassword = null;
@@ -387,7 +423,8 @@ public class SlingAuthenticator implements Authenticator,
if (HTTP_AUTH_DISABLED.equals(http)) {
this.httpBasicHandler = null;
} else {
- this.httpBasicHandler = new HttpBasicAuthenticationHandler(config.auth_http_realm(), HTTP_AUTH_ENABLED.equals(http));
+ this.httpBasicHandler =
+ new HttpBasicAuthenticationHandler(config.auth_http_realm(), HTTP_AUTH_ENABLED.equals(http));
}
}
@@ -425,8 +462,7 @@ public class SlingAuthenticator implements Authenticator,
* is terminated.
*/
@Override
- public boolean handleSecurity(HttpServletRequest request,
- HttpServletResponse response) {
+ public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) {
// 0. Nothing to do, if the session is also in the request
// this might be the case if the request is handled as a result
// of a servlet container include inside another Sling request
@@ -468,11 +504,9 @@ public class SlingAuthenticator implements Authenticator,
private boolean doHandleSecurity(HttpServletRequest request, HttpServletResponse response) {
// 0. Check for request attribute; set if not present
- Object authUriSufficesAttr = request
- .getAttribute(AuthConstants.ATTR_REQUEST_AUTH_URI_SUFFIX);
+ Object authUriSufficesAttr = request.getAttribute(AuthConstants.ATTR_REQUEST_AUTH_URI_SUFFIX);
if (authUriSufficesAttr == null && authUriSuffices != null) {
- request.setAttribute(AuthConstants.ATTR_REQUEST_AUTH_URI_SUFFIX,
- authUriSuffices);
+ request.setAttribute(AuthConstants.ATTR_REQUEST_AUTH_URI_SUFFIX, authUriSuffices);
}
// 1. Ask all authentication handlers to try to extract credentials
@@ -510,7 +544,6 @@ public class SlingAuthenticator implements Authenticator,
log.debug("doHandleSecurity: Trying to get a session for {}", authInfo.getUser());
return getResolver(request, response, authInfo);
-
}
}
@@ -541,24 +574,24 @@ public class SlingAuthenticator implements Authenticator,
}
// select path used for authentication handler selection
- final Collection<AbstractAuthenticationHandlerHolder>[] holdersArray = this.authHandlersManager
- .findApplicableHolders(request);
+ final Collection<AbstractAuthenticationHandlerHolder>[] holdersArray =
+ this.authHandlersManager.findApplicableHolders(request);
final String path = getHandlerSelectionPath(request);
boolean done = false;
for (int m = 0; !done && m < holdersArray.length; m++) {
final Collection<AbstractAuthenticationHandlerHolder> holderList = holdersArray[m];
- if ( holderList != null ) {
+ if (holderList != null) {
for (AbstractAuthenticationHandlerHolder holder : holderList) {
if (holder.isPathRequiresHandler(path)) {
- log.debug("login: requesting authentication using handler: {}",
- holder);
+ log.debug("login: requesting authentication using handler: {}", holder);
try {
done = holder.requestCredentials(request, response);
} catch (IOException ioe) {
log.error(
- "login: Failed sending authentication request through handler "
- + holder + ", access forbidden", ioe);
+ "login: Failed sending authentication request through handler " + holder
+ + ", access forbidden",
+ ioe);
done = true;
}
if (done) {
@@ -604,22 +637,19 @@ public class SlingAuthenticator implements Authenticator,
setSudoCookie(request, response, new AuthenticationInfo("dummy", request.getRemoteUser()));
final String path = getHandlerSelectionPath(request);
- final Collection<AbstractAuthenticationHandlerHolder>[] holdersArray = this.authHandlersManager
- .findApplicableHolders(request);
+ final Collection<AbstractAuthenticationHandlerHolder>[] holdersArray =
+ this.authHandlersManager.findApplicableHolders(request);
for (int m = 0; m < holdersArray.length; m++) {
final Collection<AbstractAuthenticationHandlerHolder> holderSet = holdersArray[m];
if (holderSet != null) {
for (AbstractAuthenticationHandlerHolder holder : holderSet) {
if (holder.isPathRequiresHandler(path)) {
- log.debug("logout: dropping authentication using handler: {}",
- holder);
+ log.debug("logout: dropping authentication using handler: {}", holder);
try {
holder.dropCredentials(request, response);
} catch (IOException ioe) {
- log.error(
- "logout: Failed dropping authentication through handler "
- + holder, ioe);
+ log.error("logout: Failed dropping authentication through handler " + holder, ioe);
}
}
}
@@ -634,21 +664,30 @@ public class SlingAuthenticator implements Authenticator,
}
@Override
- public void login(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) {
- this.login(JavaxToJakartaRequestWrapper.toJakartaRequest(request),
- JavaxToJakartaResponseWrapper.toJakartaResponse(response));
+ public void login(
+ final javax.servlet.http.HttpServletRequest request,
+ final javax.servlet.http.HttpServletResponse response) {
+ this.login(
+ JavaxToJakartaRequestWrapper.toJakartaRequest(request),
+ JavaxToJakartaResponseWrapper.toJakartaResponse(response));
}
@Override
- public void logout(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) {
- this.logout(JavaxToJakartaRequestWrapper.toJakartaRequest(request),
- JavaxToJakartaResponseWrapper.toJakartaResponse(response));
+ public void logout(
+ final javax.servlet.http.HttpServletRequest request,
+ final javax.servlet.http.HttpServletResponse response) {
+ this.logout(
+ JavaxToJakartaRequestWrapper.toJakartaRequest(request),
+ JavaxToJakartaResponseWrapper.toJakartaResponse(response));
}
@Override
- public boolean handleSecurity(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) {
- return this.handleSecurity(JavaxToJakartaRequestWrapper.toJakartaRequest(request),
- JavaxToJakartaResponseWrapper.toJakartaResponse(response));
+ public boolean handleSecurity(
+ final javax.servlet.http.HttpServletRequest request,
+ final javax.servlet.http.HttpServletResponse response) {
+ return this.handleSecurity(
+ JavaxToJakartaRequestWrapper.toJakartaRequest(request),
+ JavaxToJakartaResponseWrapper.toJakartaResponse(response));
}
// ---------- ServletRequestListener
@@ -698,22 +737,19 @@ public class SlingAuthenticator implements Authenticator,
String path = getPath(request);
- final Collection<AbstractAuthenticationHandlerHolder>[] localArray = this.authHandlersManager
- .findApplicableHolders(request);
+ final Collection<AbstractAuthenticationHandlerHolder>[] localArray =
+ this.authHandlersManager.findApplicableHolders(request);
for (int m = 0; m < localArray.length; m++) {
final Collection<AbstractAuthenticationHandlerHolder> local = localArray[m];
if (local != null) {
for (AbstractAuthenticationHandlerHolder holder : local) {
- if (holder.isPathRequiresHandler(path)){
- final AuthenticationInfo authInfo = holder.extractCredentials(
- request, response);
+ if (holder.isPathRequiresHandler(path)) {
+ final AuthenticationInfo authInfo = holder.extractCredentials(request, response);
if (authInfo != null) {
// skip the put call for known read-only objects
- if (authInfo != AuthenticationInfo.DOING_AUTH &&
- authInfo != AuthenticationInfo.FAIL_AUTH) {
+ if (authInfo != AuthenticationInfo.DOING_AUTH && authInfo != AuthenticationInfo.FAIL_AUTH) {
// add the feedback handler to the info (may be null)
- authInfo.put(AUTH_INFO_PROP_FEEDBACK_HANDLER,
- holder.getFeedbackHandler());
+ authInfo.put(AUTH_INFO_PROP_FEEDBACK_HANDLER, holder.getFeedbackHandler());
}
return authInfo;
}
@@ -724,8 +760,7 @@ public class SlingAuthenticator implements Authenticator,
// check whether the HTTP Basic handler can extract the header
if (httpBasicHandler != null) {
- final AuthenticationInfo authInfo = httpBasicHandler.extractCredentials(
- request, response);
+ final AuthenticationInfo authInfo = httpBasicHandler.extractCredentials(request, response);
if (authInfo != null) {
authInfo.put(AUTH_INFO_PROP_FEEDBACK_HANDLER, httpBasicHandler);
return authInfo;
@@ -742,15 +777,17 @@ public class SlingAuthenticator implements Authenticator,
*/
@SuppressWarnings("deprecation")
private void postProcess(AuthenticationInfo info, HttpServletRequest request, HttpServletResponse response)
- throws LoginException {
+ throws LoginException {
final List<JakartaAuthenticationInfoPostProcessor> localList = this.jakartaAuthInfoPostProcessors;
for (final JakartaAuthenticationInfoPostProcessor processor : localList) {
processor.postProcess(info, request, response);
}
final List<AuthenticationInfoPostProcessor> localListDep = this.authInfoPostProcessors;
for (final AuthenticationInfoPostProcessor processor : localListDep) {
- processor.postProcess(info, JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response));
+ processor.postProcess(
+ info,
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response));
}
}
@@ -762,12 +799,12 @@ public class SlingAuthenticator implements Authenticator,
* is assumed a response has been sent to the client and the request
* is terminated.
*/
- private boolean getResolver(final HttpServletRequest request,
- final HttpServletResponse response,
- final AuthenticationInfo authInfo) {
+ private boolean getResolver(
+ final HttpServletRequest request, final HttpServletResponse response, final AuthenticationInfo authInfo) {
// prepare the feedback handler
- final JakartaAuthenticationFeedbackHandler feedbackHandler = (JakartaAuthenticationFeedbackHandler) authInfo.remove(AUTH_INFO_PROP_FEEDBACK_HANDLER);
+ final JakartaAuthenticationFeedbackHandler feedbackHandler =
+ (JakartaAuthenticationFeedbackHandler) authInfo.remove(AUTH_INFO_PROP_FEEDBACK_HANDLER);
final Object sendLoginEvent = authInfo.remove(AuthConstants.AUTH_INFO_LOGIN);
// try to connect
@@ -816,8 +853,7 @@ public class SlingAuthenticator implements Authenticator,
// handle failure feedback before proceeding to handling the
// failed login internally
if (feedbackHandler != null) {
- feedbackHandler.authenticationFailed(request, response,
- authInfo);
+ feedbackHandler.authenticationFailed(request, response, authInfo);
}
// now find a way to get credentials unless the feedback handler
@@ -825,12 +861,10 @@ public class SlingAuthenticator implements Authenticator,
if (!response.isCommitted()) {
return handleLoginFailure(request, response, authInfo, re);
}
-
}
// end request
return false;
-
}
private boolean expectAuthenticationHandler(final HttpServletRequest request) {
@@ -843,11 +877,11 @@ public class SlingAuthenticator implements Authenticator,
}
}
return false;
- }
+ }
/** Try to acquire an anonymous ResourceResolver */
- private boolean getAnonymousResolver(final HttpServletRequest request,
- final HttpServletResponse response, final AuthenticationInfo authInfo) {
+ private boolean getAnonymousResolver(
+ final HttpServletRequest request, final HttpServletResponse response, final AuthenticationInfo authInfo) {
// Get an anonymous session if allowed, or if we are handling
// a request for the login servlet
@@ -877,7 +911,6 @@ public class SlingAuthenticator implements Authenticator,
// cannot login > fail login, do not try to authenticate
handleLoginFailure(request, response, new AuthenticationInfo(null, "anonymous user"), re);
return false;
-
}
}
@@ -894,7 +927,8 @@ public class SlingAuthenticator implements Authenticator,
String path = getPath(request);
- final Collection<AuthenticationRequirementHolder>[] holderSetArray = this.authenticationRequirementsManager.findApplicableHolders(request);
+ final Collection<AuthenticationRequirementHolder>[] holderSetArray =
+ this.authenticationRequirementsManager.findApplicableHolders(request);
for (int m = 0; m < holderSetArray.length; m++) {
final Collection<AuthenticationRequirementHolder> holders = holderSetArray[m];
if (holders != null) {
@@ -927,8 +961,10 @@ public class SlingAuthenticator implements Authenticator,
return info;
}
- private boolean handleLoginFailure(final HttpServletRequest request,
- final HttpServletResponse response, final AuthenticationInfo authInfo,
+ private boolean handleLoginFailure(
+ final HttpServletRequest request,
+ final HttpServletResponse response,
+ final AuthenticationInfo authInfo,
final Exception reason) {
String user = authInfo.getUser();
@@ -936,22 +972,21 @@ public class SlingAuthenticator implements Authenticator,
if (reason.getClass().getName().contains("TooManySessionsException")) {
// to many users, send a 503 Service Unavailable
- log.info("handleLoginFailure: Too many sessions for {}: {}", user,
- reason.getMessage());
+ log.info("handleLoginFailure: Too many sessions for {}: {}", user, reason.getMessage());
try {
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
- "SlingAuthenticator: Too Many Users");
+ response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "SlingAuthenticator: Too Many Users");
} catch (IOException ioe) {
- log.error(
- "handleLoginFailure: Cannot send status 503 to client", ioe);
+ log.error("handleLoginFailure: Cannot send status 503 to client", ioe);
}
} else if (reason instanceof LoginException) {
- log.info("handleLoginFailure: Unable to authenticate {}: {}", user,
- reason.getMessage());
- if (isAnonAllowed(request) && !expectAuthenticationHandler(request) && !AuthUtil.isValidateRequest(request)) {
- log.debug("handleLoginFailure: LoginException on an anonymous resource, fallback to getAnonymousResolver");
+ log.info("handleLoginFailure: Unable to authenticate {}: {}", user, reason.getMessage());
+ if (isAnonAllowed(request)
+ && !expectAuthenticationHandler(request)
+ && !AuthUtil.isValidateRequest(request)) {
+ log.debug(
+ "handleLoginFailure: LoginException on an anonymous resource, fallback to getAnonymousResolver");
processRequest = getAnonymousResolver(request, response, new AuthenticationInfo(null));
} else {
// request authentication information and send 403 (Forbidden)
@@ -960,26 +995,26 @@ public class SlingAuthenticator implements Authenticator,
FAILURE_REASON_CODES code = FailureCodesMapper.getFailureReason(authInfo, reason);
String message = null;
switch (code) {
- case ACCOUNT_LOCKED:
- message = "Account is locked";
- break;
- case ACCOUNT_NOT_FOUND:
- message = "Account was not found";
- break;
- case PASSWORD_EXPIRED:
- message = "Password expired";
- break;
- case PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY:
- message = "Password expired and new password found in password history";
- break;
- case EXPIRED_TOKEN:
- message = "Expired authentication token";
- break;
- case UNKNOWN:
- case INVALID_LOGIN:
- default:
- message = "User name and password do not match";
- break;
+ case ACCOUNT_LOCKED:
+ message = "Account is locked";
+ break;
+ case ACCOUNT_NOT_FOUND:
+ message = "Account was not found";
+ break;
+ case PASSWORD_EXPIRED:
+ message = "Password expired";
+ break;
+ case PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY:
+ message = "Password expired and new password found in password history";
+ break;
+ case EXPIRED_TOKEN:
+ message = "Expired authentication token";
+ break;
+ case UNKNOWN:
+ case INVALID_LOGIN:
+ default:
+ message = "User name and password do not match";
+ break;
}
// preset a reason for the login failure
@@ -993,26 +1028,21 @@ public class SlingAuthenticator implements Authenticator,
if (log.isErrorEnabled()) {
// general problem, send a 500 Internal Server Error
- log.error(String.format("handleLoginFailure: Unable to authenticate %s", user),
- reason);
+ log.error(String.format("handleLoginFailure: Unable to authenticate %s", user), reason);
}
try {
response.sendError(
- HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- "SlingAuthenticator: data access error, reason="
- + reason.getClass().getSimpleName());
+ HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
+ "SlingAuthenticator: data access error, reason="
+ + reason.getClass().getSimpleName());
} catch (IOException ioe) {
- log.error(
- "handleLoginFailure: Cannot send status 500 to client", ioe);
+ log.error("handleLoginFailure: Cannot send status 500 to client", ioe);
}
}
return processRequest;
-
}
-
-
/**
* Tries to request credentials from the client. The following mechanisms
* are implemented by this method:
@@ -1065,8 +1095,7 @@ public class SlingAuthenticator implements Authenticator,
* @see AuthUtil#sendInvalid(HttpServletRequest,
* HttpServletResponse)
*/
- private void doLogin(HttpServletRequest request,
- HttpServletResponse response) {
+ private void doLogin(HttpServletRequest request, HttpServletResponse response) {
if (!AuthUtil.isValidateRequest(request)) {
@@ -1092,7 +1121,6 @@ public class SlingAuthenticator implements Authenticator,
*/
log.error("doLogin: Cannot login: No AuthenticationHandler available to handle the request");
-
}
}
@@ -1106,7 +1134,6 @@ public class SlingAuthenticator implements Authenticator,
httpBasicHandler.sendUnauthorized(response);
return;
}
-
}
}
@@ -1116,14 +1143,14 @@ public class SlingAuthenticator implements Authenticator,
// credential validation
// ensure a failure reason
- ensureAttribute(request, JakartaAuthenticationHandler.FAILURE_REASON,
- "Authentication Failed");
+ ensureAttribute(request, JakartaAuthenticationHandler.FAILURE_REASON, "Authentication Failed");
AuthUtil.sendInvalid(request, response);
}
private boolean isExpiredToken(HttpServletRequest request) {
- return FAILURE_REASON_CODES.EXPIRED_TOKEN == request.getAttribute(JakartaAuthenticationHandler.FAILURE_REASON_CODE);
+ return FAILURE_REASON_CODES.EXPIRED_TOKEN
+ == request.getAttribute(JakartaAuthenticationHandler.FAILURE_REASON_CODE);
}
/**
@@ -1138,8 +1165,7 @@ public class SlingAuthenticator implements Authenticator,
*/
private boolean isLoginLoop(final HttpServletRequest request) {
- if (isExpiredToken(request))
- return false;
+ if (isExpiredToken(request)) return false;
String referer = request.getHeader("Referer");
if (referer != null) {
@@ -1162,8 +1188,7 @@ public class SlingAuthenticator implements Authenticator,
* @param attribute The name of the attribute to check/set
* @param value The value to set the attribute to if it is not already set
*/
- private void ensureAttribute(final HttpServletRequest request,
- final String attribute, final Object value) {
+ private void ensureAttribute(final HttpServletRequest request, final String attribute, final Object value) {
if (request.getAttribute(attribute) == null) {
request.setAttribute(attribute, value);
}
@@ -1175,21 +1200,19 @@ public class SlingAuthenticator implements Authenticator,
* {@link SlingAuthenticator#REQUEST_ATTRIBUTE_RESOLVER} request attribute
* is set to the ResourceResolver.
*/
- private void setAttributes(final ResourceResolver resolver, final String authType,
- final HttpServletRequest request) {
+ private void setAttributes(
+ final ResourceResolver resolver, final String authType, final HttpServletRequest request) {
// HttpService API required attributes
request.setAttribute(ServletContextHelper.AUTHENTICATION_TYPE, authType);
- if ( authType != null ) {
+ if (authType != null) {
request.setAttribute(ServletContextHelper.REMOTE_USER, resolver.getUserID());
}
// resource resolver for down-stream use
request.setAttribute(REQUEST_ATTRIBUTE_RESOLVER, resolver);
- log.debug(
- "setAttributes: ResourceResolver stored as request attribute: user={}",
- resolver.getUserID());
+ log.debug("setAttributes: ResourceResolver stored as request attribute: user={}", resolver.getUserID());
}
/**
@@ -1216,7 +1239,9 @@ public class SlingAuthenticator implements Authenticator,
private void sendSudoCookie(
HttpServletRequest request,
HttpServletResponse response,
- final String user, final int maxAge, final String path,
+ final String user,
+ final int maxAge,
+ final String path,
final String owner) {
final String quotedUser;
@@ -1228,14 +1253,18 @@ public class SlingAuthenticator implements Authenticator,
}
} catch (IllegalArgumentException iae) {
log.error(
- "sendSudoCookie: Failed to quote value '{}' of cookie {}: {}",
- user, this.sudoCookieName, iae.getMessage());
+ "sendSudoCookie: Failed to quote value '{}' of cookie {}: {}",
+ user,
+ this.sudoCookieName,
+ iae.getMessage());
return;
} catch (UnsupportedEncodingException e) {
log.error(
"sendSudoCookie: Failed to quote value '{}' of cookie {}: {}",
- user, this.sudoCookieName, e.getMessage());
- return;
+ user,
+ this.sudoCookieName,
+ e.getMessage());
+ return;
}
if (quotedUser != null) {
@@ -1245,7 +1274,7 @@ public class SlingAuthenticator implements Authenticator,
cookie.setMaxAge(maxAge);
cookie.setPath((path == null || path.length() == 0) ? "/" : path);
try {
- cookie.setComment(quotedOwner + " impersonates as " +quotedUser);
+ cookie.setComment(quotedOwner + " impersonates as " + quotedUser);
} catch (IllegalArgumentException iae) {
// ignore
}
@@ -1271,8 +1300,7 @@ public class SlingAuthenticator implements Authenticator,
* <code>sudo.user.id</code> property is set to the impersonator
* user.
*/
- private void handleImpersonation(HttpServletRequest req,
- AuthenticationInfo authInfo) {
+ private void handleImpersonation(HttpServletRequest req, AuthenticationInfo authInfo) {
String currentSudo = getSudoCookieValue(req);
/**
@@ -1307,7 +1335,7 @@ public class SlingAuthenticator implements Authenticator,
* <code>newPassword</code> property is set.
*/
private void handlePasswordChange(HttpServletRequest req, AuthenticationInfo authInfo) {
- String newPassword = req.getParameter(PAR_NEW_PASSWORD );
+ String newPassword = req.getParameter(PAR_NEW_PASSWORD);
if (newPassword != null && newPassword.length() > 0) {
authInfo.put("user.newpassword", newPassword);
}
@@ -1343,8 +1371,7 @@ public class SlingAuthenticator implements Authenticator,
* @return <code>true</code> if the cookie has been set or cleared or
* <code>false</code> if the cookie is not modified.
*/
- boolean setSudoCookie(HttpServletRequest req,
- HttpServletResponse res, AuthenticationInfo authInfo) {
+ boolean setSudoCookie(HttpServletRequest req, HttpServletResponse res, AuthenticationInfo authInfo) {
final String sudo = (String) authInfo.get(ResourceResolverFactory.USER_IMPERSONATION);
final String currentSudo = getSudoCookieValue(req);
@@ -1390,7 +1417,7 @@ public class SlingAuthenticator implements Authenticator,
if (loginPathO instanceof String) {
path = (String) loginPathO;
final String ctxPath = request.getContextPath();
- if (ctxPath != null && path.startsWith(ctxPath)) {
+ if (ctxPath != null && path.startsWith(ctxPath)) {
path = path.substring(ctxPath.length());
}
if (path == null || path.length() == 0) {
@@ -1416,8 +1443,7 @@ public class SlingAuthenticator implements Authenticator,
* @param request The request providing the redirect target
* @param response The response to send the redirect to
*/
- private void redirectAfterLogout(final HttpServletRequest request,
- final HttpServletResponse response) {
+ private void redirectAfterLogout(final HttpServletRequest request, final HttpServletResponse response) {
// nothing more to do if the response has already been committed
if (response.isCommitted()) {
@@ -1468,11 +1494,11 @@ public class SlingAuthenticator implements Authenticator,
* to the {@link AuthConstants#TOPIC_LOGIN_FAILED} event topic may be used to implement a failed login throttling solution.
*/
@SuppressWarnings("deprecation")
- private void postLoginFailedEvent(final HttpServletRequest request,
- final AuthenticationInfo authInfo, Exception reason) {
+ private void postLoginFailedEvent(
+ final HttpServletRequest request, final AuthenticationInfo authInfo, Exception reason) {
// The reason for the failure may be useful to downstream subscribers.
FAILURE_REASON_CODES reasonCode = FailureCodesMapper.getFailureReason(authInfo, reason);
- //if reason code is unknowm, it is problem some non-login related failure, so don't send the event
+ // if reason code is unknowm, it is problem some non-login related failure, so don't send the event
if (reasonCode != FAILURE_REASON_CODES.UNKNOWN) {
final Map<String, Object> properties = new HashMap<>();
if (authInfo.getUser() != null) {
@@ -1490,7 +1516,8 @@ public class SlingAuthenticator implements Authenticator,
}
final List<LoginEventDecorator> localListDep = this.loginEventDecorators;
for (final LoginEventDecorator decorator : localListDep) {
- decorator.decorateLoginFailedEvent(JakartaToJavaxRequestWrapper.toJavaxRequest(request), authInfo, properties);
+ decorator.decorateLoginFailedEvent(
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request), authInfo, properties);
}
EventAdmin localEA = this.eventAdmin;
@@ -1541,8 +1568,7 @@ public class SlingAuthenticator implements Authenticator,
} else if (c == '@') {
builder.append(c);
} else if (c == 127 || (c < 32 && c != '\t')) {
- throw new IllegalArgumentException(
- "Cookie value may not contain CTL character");
+ throw new IllegalArgumentException("Cookie value may not contain CTL character");
} else {
builder.append(URLEncoder.encode(String.valueOf(c), "UTF-8"));
}
@@ -1568,12 +1594,12 @@ public class SlingAuthenticator implements Authenticator,
}
if (value.startsWith("\"") && value.endsWith("\"")) {
- value = value.substring(1, value.length()-1);
+ value = value.substring(1, value.length() - 1);
}
StringBuilder builder = new StringBuilder();
- String [] values = value.split("\\\\");
- for (String v:values) {
+ String[] values = value.split("\\\\");
+ for (String v : values) {
try {
builder.append(URLDecoder.decode(v, "UTF-8"));
} catch (UnsupportedEncodingException e) {
diff --git a/src/main/java/org/apache/sling/auth/core/impl/engine/EngineAuthenticationHandlerHolder.java b/src/main/java/org/apache/sling/auth/core/impl/engine/EngineAuthenticationHandlerHolder.java
index 077fd22..6b1a001 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/engine/EngineAuthenticationHandlerHolder.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/engine/EngineAuthenticationHandlerHolder.java
@@ -23,7 +23,6 @@ import java.util.Objects;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.wrappers.JakartaToJavaxRequestWrapper;
import org.apache.sling.api.wrappers.JakartaToJavaxResponseWrapper;
import org.apache.sling.auth.core.impl.AbstractAuthenticationHandlerHolder;
@@ -40,15 +39,13 @@ import org.osgi.framework.ServiceReference;
* {@link org.apache.sling.auth.core.impl.SlingAuthenticator}.
*/
@SuppressWarnings("deprecation")
-public final class EngineAuthenticationHandlerHolder extends
- AbstractAuthenticationHandlerHolder {
+public final class EngineAuthenticationHandlerHolder extends AbstractAuthenticationHandlerHolder {
// the actual authentication handler
private final AuthenticationHandler handler;
- public EngineAuthenticationHandlerHolder(final String fullPath,
- final AuthenticationHandler handler,
- final ServiceReference<?> serviceReference) {
+ public EngineAuthenticationHandlerHolder(
+ final String fullPath, final AuthenticationHandler handler, final ServiceReference<?> serviceReference) {
super(fullPath, serviceReference);
this.handler = handler;
}
@@ -59,31 +56,34 @@ public final class EngineAuthenticationHandlerHolder extends
return new JakartaAuthenticationFeedbackHandler() {
@Override
- public void authenticationFailed(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo) {
- ((AuthenticationFeedbackHandler) handler).authenticationFailed(
- JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response), authInfo);
+ public void authenticationFailed(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
+ ((AuthenticationFeedbackHandler) handler)
+ .authenticationFailed(
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response),
+ authInfo);
}
@Override
- public boolean authenticationSucceeded(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo) {
- return ((AuthenticationFeedbackHandler) handler).authenticationSucceeded(
- JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response), authInfo);
+ public boolean authenticationSucceeded(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
+ return ((AuthenticationFeedbackHandler) handler)
+ .authenticationSucceeded(
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response),
+ authInfo);
}
};
}
return null;
}
- public AuthenticationInfo doExtractCredentials(HttpServletRequest request,
- HttpServletResponse response) {
+ public AuthenticationInfo doExtractCredentials(HttpServletRequest request, HttpServletResponse response) {
org.apache.sling.engine.auth.AuthenticationInfo engineAuthInfo = handler.authenticate(
- JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response));
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response));
if (engineAuthInfo == null) {
return null;
} else if (engineAuthInfo == org.apache.sling.engine.auth.AuthenticationInfo.DOING_AUTH) {
@@ -92,22 +92,20 @@ public final class EngineAuthenticationHandlerHolder extends
// backwards compatibility support for JCR credentials and workspace
// name now encapsulated in the JCR Resource bundle
- AuthenticationInfo info = new AuthenticationInfo(
- engineAuthInfo.getAuthType());
+ AuthenticationInfo info = new AuthenticationInfo(engineAuthInfo.getAuthType());
info.put("user.jcr.credentials", engineAuthInfo.getCredentials());
info.put("user.jcr.workspace", engineAuthInfo.getWorkspaceName());
return info;
}
- public boolean doRequestCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
- return handler.requestAuthentication(JakartaToJavaxRequestWrapper.toJavaxRequest(request),
- JakartaToJavaxResponseWrapper.toJavaxResponse(response));
+ public boolean doRequestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ return handler.requestAuthentication(
+ JakartaToJavaxRequestWrapper.toJavaxRequest(request),
+ JakartaToJavaxResponseWrapper.toJavaxResponse(response));
}
- public void doDropCredentials(HttpServletRequest request,
- HttpServletResponse response) {
+ public void doDropCredentials(HttpServletRequest request, HttpServletResponse response) {
// Engine AuthenticationHandler does not have this method
}
@@ -121,12 +119,9 @@ public final class EngineAuthenticationHandlerHolder extends
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
+ if (getClass() != obj.getClass()) return false;
EngineAuthenticationHandlerHolder other = (EngineAuthenticationHandlerHolder) obj;
return Objects.equals(handler, other.handler);
}
@@ -135,5 +130,4 @@ public final class EngineAuthenticationHandlerHolder extends
public String toString() {
return handler.toString() + " (Legacy API Handler)";
}
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/engine/EngineSlingAuthenticator.java b/src/main/java/org/apache/sling/auth/core/impl/engine/EngineSlingAuthenticator.java
index 6680dc3..b492e73 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/engine/EngineSlingAuthenticator.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/engine/EngineSlingAuthenticator.java
@@ -57,5 +57,4 @@ public class EngineSlingAuthenticator implements Authenticator {
public void logout(HttpServletRequest request, HttpServletResponse response) {
slingAuthenticator.logout(request, response);
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheck.java b/src/main/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheck.java
index a02f373..36a8861 100644
--- a/src/main/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheck.java
+++ b/src/main/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheck.java
@@ -1,30 +1,31 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
+ * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
- * regarding copyright ownership. The SF licenses this file
+ * regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations under the License.
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl.hc;
-import java.util.Arrays;
-import java.util.List;
-
import javax.jcr.Credentials;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
+import java.util.Arrays;
+import java.util.List;
+
import org.apache.felix.hc.api.FormattingResultLog;
import org.apache.felix.hc.api.HealthCheck;
import org.apache.felix.hc.api.Result;
@@ -40,7 +41,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** {@link HealthCheck} that runs an arbitrary script. */
-@Component(service = HealthCheck.class, name = "org.apache.sling.auth.core.DefaultLoginsHealthCheck", configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(
+ service = HealthCheck.class,
+ name = "org.apache.sling.auth.core.DefaultLoginsHealthCheck",
+ configurationPolicy = ConfigurationPolicy.REQUIRE)
@Designate(ocd = DefaultLoginsHealthCheck.Config.class, factory = true)
public class DefaultLoginsHealthCheck implements HealthCheck {
@@ -48,18 +52,26 @@ public class DefaultLoginsHealthCheck implements HealthCheck {
public static final String HC_LABEL = "Health Check: Default Logins";
- @ObjectClassDefinition(name = HC_LABEL, description = "Expects default logins to fail, used to verify that they are disabled on production systems")
+ @ObjectClassDefinition(
+ name = HC_LABEL,
+ description = "Expects default logins to fail, used to verify that they are disabled on production systems")
@interface Config {
@AttributeDefinition(name = "Name", description = "Name of this health check.")
String hc_name() default "Default Logins Check"; // NOSONAR
- @AttributeDefinition(name = "Tags", description = "List of tags for this health check, used to select subsets of health checks for execution e.g. by a composite health check.")
+ @AttributeDefinition(
+ name = "Tags",
+ description =
+ "List of tags for this health check, used to select subsets of health checks for execution e.g. by a composite health check.")
String[] hc_tags() default {}; // NOSONAR
- @AttributeDefinition(name = "Default Logins", description = "Which credentials to check. Each one is in the format"
- + " \"user:password\" like \"admin:admin\" for example. Do *not* put any confidential passwords here, the goal "
- + "is just to check that the default/demo logins, which passwords are known anyway, are disabled.")
+ @AttributeDefinition(
+ name = "Default Logins",
+ description =
+ "Which credentials to check. Each one is in the format"
+ + " \"user:password\" like \"admin:admin\" for example. Do *not* put any confidential passwords here, the goal "
+ + "is just to check that the default/demo logins, which passwords are known anyway, are disabled.")
String[] logins() default "logins";
@AttributeDefinition
@@ -121,5 +133,4 @@ public class DefaultLoginsHealthCheck implements HealthCheck {
return new Result(resultLog);
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/package-info.java b/src/main/java/org/apache/sling/auth/core/package-info.java
index 5b86e9f..4102d58 100755
--- a/src/main/java/org/apache/sling/auth/core/package-info.java
+++ b/src/main/java/org/apache/sling/auth/core/package-info.java
@@ -26,5 +26,3 @@
*/
@org.osgi.annotation.versioning.Version("1.6.0")
package org.apache.sling.auth.core;
-
-
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationFormServlet.java b/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationFormServlet.java
index 7df18f8..ee22c3a 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationFormServlet.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationFormServlet.java
@@ -18,6 +18,10 @@
*/
package org.apache.sling.auth.core.spi;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -25,10 +29,6 @@ import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.sling.auth.core.AuthUtil;
/**
@@ -77,8 +77,7 @@ public abstract class AbstractAuthenticationFormServlet extends HttpServlet {
* and thus response reset is not possible.
*/
@Override
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
handle(request, response);
}
@@ -97,8 +96,7 @@ public abstract class AbstractAuthenticationFormServlet extends HttpServlet {
* and thus response reset is not possible.
*/
@Override
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
handle(request, response);
}
@@ -138,8 +136,7 @@ public abstract class AbstractAuthenticationFormServlet extends HttpServlet {
* @return The login form to be returned to the client
* @throws IOException If the login form cannot be loaded
*/
- protected String getForm(final HttpServletRequest request)
- throws IOException {
+ protected String getForm(final HttpServletRequest request) throws IOException {
String form = getRawForm();
final String resource = cleanse(request, getResource(request));
@@ -192,9 +189,9 @@ public abstract class AbstractAuthenticationFormServlet extends HttpServlet {
}
final StringBuilder b = new StringBuilder(input.length());
- for(int i = 0;i < input.length(); i++) {
+ for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
- if(c == '&') {
+ if (c == '&') {
b.append("&");
} else if (c == '<') {
b.append("<");
@@ -260,7 +257,7 @@ public abstract class AbstractAuthenticationFormServlet extends HttpServlet {
}
private static String removeEndingSlash(String str) {
- if(str != null && str.endsWith("/")) {
+ if (str != null && str.endsWith("/")) {
return str.substring(0, str.length() - 1);
}
return str;
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationHandler.java b/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationHandler.java
index a7635dc..fc6532d 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AbstractAuthenticationHandler.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.auth.core.spi;
-import java.io.IOException;
-import java.util.Map;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+
import org.apache.sling.auth.core.AuthUtil;
/**
@@ -38,8 +38,8 @@ import org.apache.sling.auth.core.AuthUtil;
* class.
*/
@Deprecated
-public abstract class AbstractAuthenticationHandler extends DefaultAuthenticationFeedbackHandler implements
- AuthenticationHandler {
+public abstract class AbstractAuthenticationHandler extends DefaultAuthenticationFeedbackHandler
+ implements AuthenticationHandler {
/**
* Returns the value of the named request attribute or parameter as a string
@@ -65,8 +65,8 @@ public abstract class AbstractAuthenticationHandler extends DefaultAuthenticatio
* {@link AuthUtil#getAttributeOrParameter(HttpServletRequest, String, String)}
*/
@Deprecated
- public static String getAttributeOrParameter(final HttpServletRequest request, final String name,
- final String defaultValue) {
+ public static String getAttributeOrParameter(
+ final HttpServletRequest request, final String name, final String defaultValue) {
return AuthUtil.getAttributeOrParameter(request, name, defaultValue);
}
@@ -166,8 +166,12 @@ public abstract class AbstractAuthenticationHandler extends DefaultAuthenticatio
* {@link AuthUtil#sendRedirect(HttpServletRequest, HttpServletResponse, String, Map)}
*/
@Deprecated
- public static void sendRedirect(final HttpServletRequest request, final HttpServletResponse response,
- final String target, Map<String, String> params) throws IOException {
+ public static void sendRedirect(
+ final HttpServletRequest request,
+ final HttpServletResponse response,
+ final String target,
+ Map<String, String> params)
+ throws IOException {
AuthUtil.sendRedirect(request, response, request.getContextPath() + target, params);
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AbstractJakartaAuthenticationFormServlet.java b/src/main/java/org/apache/sling/auth/core/spi/AbstractJakartaAuthenticationFormServlet.java
index a153876..93b7ab0 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AbstractJakartaAuthenticationFormServlet.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AbstractJakartaAuthenticationFormServlet.java
@@ -28,7 +28,6 @@ import java.util.concurrent.atomic.AtomicReference;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.auth.core.AuthUtil;
/**
@@ -76,8 +75,7 @@ public abstract class AbstractJakartaAuthenticationFormServlet extends HttpServl
* and thus response reset is not possible.
*/
@Override
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
handle(request, response);
}
@@ -96,8 +94,7 @@ public abstract class AbstractJakartaAuthenticationFormServlet extends HttpServl
* and thus response reset is not possible.
*/
@Override
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
handle(request, response);
}
@@ -137,8 +134,7 @@ public abstract class AbstractJakartaAuthenticationFormServlet extends HttpServl
* @return The login form to be returned to the client
* @throws IOException If the login form cannot be loaded
*/
- protected String getForm(final HttpServletRequest request)
- throws IOException {
+ protected String getForm(final HttpServletRequest request) throws IOException {
String form = getRawForm();
final String resource = cleanse(request, getResource(request));
@@ -191,9 +187,9 @@ public abstract class AbstractJakartaAuthenticationFormServlet extends HttpServl
}
final StringBuilder b = new StringBuilder(input.length());
- for(int i = 0;i < input.length(); i++) {
+ for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
- if(c == '&') {
+ if (c == '&') {
b.append("&");
} else if (c == '<') {
b.append("<");
@@ -259,7 +255,7 @@ public abstract class AbstractJakartaAuthenticationFormServlet extends HttpServl
}
private static String removeEndingSlash(String str) {
- if(str != null && str.endsWith("/")) {
+ if (str != null && str.endsWith("/")) {
return str.substring(0, str.length() - 1);
}
return str;
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationFeedbackHandler.java b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationFeedbackHandler.java
index 6930d89..5bb9c91 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationFeedbackHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationFeedbackHandler.java
@@ -57,8 +57,7 @@ public interface AuthenticationFeedbackHandler {
* @param authInfo The {@link AuthenticationInfo} object used to
* authenticate the request.
*/
- void authenticationFailed(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo);
+ void authenticationFailed(HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo);
/**
* Called if authentication succeeded with the credentials provided in the
@@ -78,6 +77,6 @@ public interface AuthenticationFeedbackHandler {
* If <code>false</code> is returned, the request proceeds as
* authenticated.
*/
- boolean authenticationSucceeded(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo);
+ boolean authenticationSucceeded(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo);
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationHandler.java b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationHandler.java
index 45740b8..8f29ed1 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationHandler.java
@@ -18,14 +18,13 @@
*/
package org.apache.sling.auth.core.spi;
-import java.io.IOException;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.osgi.annotation.versioning.ConsumerType;
+import java.io.IOException;
import aQute.bnd.annotation.baseline.BaselineIgnore;
+import org.osgi.annotation.versioning.ConsumerType;
/**
* The <code>AuthenticationHandler</code> interface defines the service API used
@@ -201,8 +200,7 @@ public interface AuthenticationHandler {
* In case of {@link AuthenticationInfo#DOING_AUTH}, the method must
* have sent a response indicating that fact to the client.
*/
- AuthenticationInfo extractCredentials(HttpServletRequest request,
- HttpServletResponse response);
+ AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response);
/**
* Requests authentication information from the client. Returns
@@ -240,8 +238,7 @@ public interface AuthenticationHandler {
* @throws IOException If an error occurs sending the authentication
* inquiry to the client.
*/
- boolean requestCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException;
/**
* Drops any credential and authentication details from the request and asks
@@ -252,6 +249,5 @@ public interface AuthenticationHandler {
* @throws IOException If an error occurs asking the client to drop any
* authentication traces.
*/
- void dropCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException;
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfo.java b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfo.java
index 0283ef0..6b622eb 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfo.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfo.java
@@ -55,7 +55,7 @@ public class AuthenticationInfo extends HashMap<String, Object> {
* no further actions should be taken on this request.
*/
public static final AuthenticationInfo DOING_AUTH = new ReadOnlyAuthenticationInfo( // NOSONAR
- "DOING_AUTH");
+ "DOING_AUTH");
/**
* A special instance of this class which may be returned from the
@@ -69,7 +69,7 @@ public class AuthenticationInfo extends HashMap<String, Object> {
* expired).
*/
public static final AuthenticationInfo FAIL_AUTH = new ReadOnlyAuthenticationInfo( // NOSONAR
- "FAIL_AUTH");
+ "FAIL_AUTH");
/**
* The name of the special property providing the authentication type
@@ -119,8 +119,7 @@ public class AuthenticationInfo extends HashMap<String, Object> {
* @throws NullPointerException if <code>authType</code> is
* <code>null</code>.
*/
- public AuthenticationInfo(final String authType, final String userId,
- final char[] password) {
+ public AuthenticationInfo(final String authType, final String userId, final char[] password) {
super.put(AUTH_TYPE, authType);
putIfNotNull(ResourceResolverFactory.USER, userId);
putIfNotNull(ResourceResolverFactory.PASSWORD, password);
@@ -219,20 +218,15 @@ public class AuthenticationInfo extends HashMap<String, Object> {
public Object put(final String key, final Object value) {
if (AUTH_TYPE.equals(key) && !(value instanceof String)) {
- throw new IllegalArgumentException(AUTH_TYPE
- + " property must be a String");
+ throw new IllegalArgumentException(AUTH_TYPE + " property must be a String");
}
- if (ResourceResolverFactory.USER.equals(key)
- && !(value instanceof String)) {
- throw new IllegalArgumentException(ResourceResolverFactory.USER
- + " property must be a String");
+ if (ResourceResolverFactory.USER.equals(key) && !(value instanceof String)) {
+ throw new IllegalArgumentException(ResourceResolverFactory.USER + " property must be a String");
}
- if (ResourceResolverFactory.PASSWORD.equals(key)
- && !(value instanceof char[])) {
- throw new IllegalArgumentException(ResourceResolverFactory.PASSWORD
- + " property must be a char[]");
+ if (ResourceResolverFactory.PASSWORD.equals(key) && !(value instanceof char[])) {
+ throw new IllegalArgumentException(ResourceResolverFactory.PASSWORD + " property must be a char[]");
}
return super.put(key, value);
@@ -288,10 +282,9 @@ public class AuthenticationInfo extends HashMap<String, Object> {
* methods that may change the state.
* This acts like kind of a read-only immutable wrapper.
*/
- private static final class ReadOnlyAuthenticationInfo extends
- AuthenticationInfo {
+ private static final class ReadOnlyAuthenticationInfo extends AuthenticationInfo {
- private final transient Map<String, Object> unmodifiableMap; // NOSONAR
+ private final transient Map<String, Object> unmodifiableMap; // NOSONAR
// used to guard against stack overflow
private final transient ThreadLocal<Boolean> stackGuard = new ThreadLocal<>();
@@ -397,19 +390,21 @@ public class AuthenticationInfo extends HashMap<String, Object> {
}
@Override
- public Object computeIfPresent(String key,
- BiFunction<? super String, ? super Object, ? extends Object> remappingFunction) {
+ public Object computeIfPresent(
+ String key, BiFunction<? super String, ? super Object, ? extends Object> remappingFunction) {
return unmodifiableMap.computeIfPresent(key, remappingFunction);
}
@Override
- public Object compute(String key,
- BiFunction<? super String, ? super Object, ? extends Object> remappingFunction) {
+ public Object compute(
+ String key, BiFunction<? super String, ? super Object, ? extends Object> remappingFunction) {
return unmodifiableMap.compute(key, remappingFunction);
}
@Override
- public Object merge(String key, Object value,
+ public Object merge(
+ String key,
+ Object value,
BiFunction<? super Object, ? super Object, ? extends Object> remappingFunction) {
return unmodifiableMap.merge(key, value, remappingFunction);
}
@@ -429,12 +424,9 @@ public class AuthenticationInfo extends HashMap<String, Object> {
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
return getClass() == obj.getClass();
}
-
}
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfoPostProcessor.java b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfoPostProcessor.java
index f354b31..d008f3d 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfoPostProcessor.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/AuthenticationInfoPostProcessor.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.spi;
@@ -60,6 +62,5 @@ public interface AuthenticationInfoPostProcessor {
* credentials
*/
void postProcess(AuthenticationInfo info, HttpServletRequest request, HttpServletResponse response)
- throws LoginException;
-
+ throws LoginException;
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/DefaultAuthenticationFeedbackHandler.java b/src/main/java/org/apache/sling/auth/core/spi/DefaultAuthenticationFeedbackHandler.java
index 63fc800..dae3d9a 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/DefaultAuthenticationFeedbackHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/DefaultAuthenticationFeedbackHandler.java
@@ -30,8 +30,7 @@ import org.slf4j.LoggerFactory;
* @deprecated Use {@link JakartaAuthenticationFeedbackHandler} instead
*/
@Deprecated
-public class DefaultAuthenticationFeedbackHandler implements
- AuthenticationFeedbackHandler {
+public class DefaultAuthenticationFeedbackHandler implements AuthenticationFeedbackHandler {
/**
* Handles an optional request for a redirect after successful
@@ -75,8 +74,7 @@ public class DefaultAuthenticationFeedbackHandler implements
* {@link AbstractAuthenticationHandler#isRedirectValid(HttpServletRequest, String)}
* method.
*/
- public static boolean handleRedirect(final HttpServletRequest request,
- final HttpServletResponse response) {
+ public static boolean handleRedirect(final HttpServletRequest request, final HttpServletResponse response) {
final String redirect = getValidatedRedirectTarget(request);
if (redirect != null) {
@@ -85,10 +83,11 @@ public class DefaultAuthenticationFeedbackHandler implements
response.sendRedirect(redirect);
} catch (Exception e) {
// expected: IOException and IllegalStateException
- LoggerFactory.getLogger(
- DefaultAuthenticationFeedbackHandler.class).error(
- "handleRedirect: Failed to send redirect to " + redirect
- + ", aborting request without redirect", e);
+ LoggerFactory.getLogger(DefaultAuthenticationFeedbackHandler.class)
+ .error(
+ "handleRedirect: Failed to send redirect to " + redirect
+ + ", aborting request without redirect",
+ e);
}
// consider the request done
@@ -99,8 +98,7 @@ public class DefaultAuthenticationFeedbackHandler implements
return false;
}
- private static String getValidatedRedirectTarget(
- final HttpServletRequest request) {
+ private static String getValidatedRedirectTarget(final HttpServletRequest request) {
String redirect = request.getParameter(AuthenticationSupport.REDIRECT_PARAMETER);
if (redirect == null) {
return null;
@@ -128,9 +126,8 @@ public class DefaultAuthenticationFeedbackHandler implements
// absolute target (in the servlet context)
if (!AuthUtil.isRedirectValid(request, redirect)) {
- LoggerFactory.getLogger(DefaultAuthenticationFeedbackHandler.class).error(
- "handleRedirect: Redirect target '{}' is invalid, redirecting to '/'",
- redirect);
+ LoggerFactory.getLogger(DefaultAuthenticationFeedbackHandler.class)
+ .error("handleRedirect: Redirect target '{}' is invalid, redirecting to '/'", redirect);
redirect = "/";
}
@@ -143,8 +140,8 @@ public class DefaultAuthenticationFeedbackHandler implements
* Extensions of this class may overwrite to cleanup any internal state.
*/
@Override
- public void authenticationFailed(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo) {
+ public void authenticationFailed(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
// no op
}
@@ -161,9 +158,8 @@ public class DefaultAuthenticationFeedbackHandler implements
* method.
*/
@Override
- public boolean authenticationSucceeded(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo) {
+ public boolean authenticationSucceeded(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
return handleRedirect(request, response);
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/DefaultJakartaAuthenticationFeedbackHandler.java b/src/main/java/org/apache/sling/auth/core/spi/DefaultJakartaAuthenticationFeedbackHandler.java
index 8348628..e2edb29 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/DefaultJakartaAuthenticationFeedbackHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/DefaultJakartaAuthenticationFeedbackHandler.java
@@ -20,7 +20,6 @@ package org.apache.sling.auth.core.spi;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.auth.core.AuthenticationSupport;
@@ -30,8 +29,7 @@ import org.slf4j.LoggerFactory;
* Default implementation of an authentication feedback handler.
* @since 1.3.0
*/
-public class DefaultJakartaAuthenticationFeedbackHandler implements
- JakartaAuthenticationFeedbackHandler {
+public class DefaultJakartaAuthenticationFeedbackHandler implements JakartaAuthenticationFeedbackHandler {
/**
* Handles an optional request for a redirect after successful
@@ -75,8 +73,7 @@ public class DefaultJakartaAuthenticationFeedbackHandler implements
* {@link AuthUtil#isRedirectValid(HttpServletRequest, String)}
* method.
*/
- public static boolean handleRedirect(final HttpServletRequest request,
- final HttpServletResponse response) {
+ public static boolean handleRedirect(final HttpServletRequest request, final HttpServletResponse response) {
final String redirect = getValidatedRedirectTarget(request);
if (redirect != null) {
@@ -85,10 +82,11 @@ public class DefaultJakartaAuthenticationFeedbackHandler implements
response.sendRedirect(redirect);
} catch (Exception e) {
// expected: IOException and IllegalStateException
- LoggerFactory.getLogger(
- DefaultJakartaAuthenticationFeedbackHandler.class).error(
- "handleRedirect: Failed to send redirect to " + redirect
- + ", aborting request without redirect", e);
+ LoggerFactory.getLogger(DefaultJakartaAuthenticationFeedbackHandler.class)
+ .error(
+ "handleRedirect: Failed to send redirect to " + redirect
+ + ", aborting request without redirect",
+ e);
}
// consider the request done
@@ -99,8 +97,7 @@ public class DefaultJakartaAuthenticationFeedbackHandler implements
return false;
}
- private static String getValidatedRedirectTarget(
- final HttpServletRequest request) {
+ private static String getValidatedRedirectTarget(final HttpServletRequest request) {
String redirect = request.getParameter(AuthenticationSupport.REDIRECT_PARAMETER);
if (redirect == null) {
return null;
@@ -128,9 +125,8 @@ public class DefaultJakartaAuthenticationFeedbackHandler implements
// absolute target (in the servlet context)
if (!AuthUtil.isRedirectValid(request, redirect)) {
- LoggerFactory.getLogger(DefaultJakartaAuthenticationFeedbackHandler.class).error(
- "handleRedirect: Redirect target '{}' is invalid, redirecting to '/'",
- redirect);
+ LoggerFactory.getLogger(DefaultJakartaAuthenticationFeedbackHandler.class)
+ .error("handleRedirect: Redirect target '{}' is invalid, redirecting to '/'", redirect);
redirect = "/";
}
@@ -143,8 +139,8 @@ public class DefaultJakartaAuthenticationFeedbackHandler implements
* Extensions of this class may overwrite to cleanup any internal state.
*/
@Override
- public void authenticationFailed(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo) {
+ public void authenticationFailed(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
// no op
}
@@ -161,9 +157,8 @@ public class DefaultJakartaAuthenticationFeedbackHandler implements
* method.
*/
@Override
- public boolean authenticationSucceeded(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo) {
+ public boolean authenticationSucceeded(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
return handleRedirect(request, response);
}
-
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationFeedbackHandler.java b/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationFeedbackHandler.java
index a40ed1d..df04063 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationFeedbackHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationFeedbackHandler.java
@@ -20,7 +20,6 @@ package org.apache.sling.auth.core.spi;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.osgi.annotation.versioning.ConsumerType;
/**
@@ -56,8 +55,7 @@ public interface JakartaAuthenticationFeedbackHandler {
* @param authInfo The {@link AuthenticationInfo} object used to
* authenticate the request.
*/
- void authenticationFailed(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo);
+ void authenticationFailed(HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo);
/**
* Called if authentication succeeded with the credentials provided in the
@@ -77,6 +75,6 @@ public interface JakartaAuthenticationFeedbackHandler {
* If <code>false</code> is returned, the request proceeds as
* authenticated.
*/
- boolean authenticationSucceeded(HttpServletRequest request,
- HttpServletResponse response, AuthenticationInfo authInfo);
+ boolean authenticationSucceeded(
+ HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo);
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationHandler.java b/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationHandler.java
index 8ae0ced..ccc9531 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationHandler.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationHandler.java
@@ -22,7 +22,6 @@ import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.osgi.annotation.versioning.ConsumerType;
/**
@@ -165,8 +164,7 @@ public interface JakartaAuthenticationHandler {
* In case of {@link AuthenticationInfo#DOING_AUTH}, the method must
* have sent a response indicating that fact to the client.
*/
- AuthenticationInfo extractCredentials(HttpServletRequest request,
- HttpServletResponse response);
+ AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response);
/**
* Requests authentication information from the client. Returns
@@ -204,8 +202,7 @@ public interface JakartaAuthenticationHandler {
* @throws IOException If an error occurs sending the authentication
* inquiry to the client.
*/
- boolean requestCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException;
/**
* Drops any credential and authentication details from the request and asks
@@ -216,6 +213,5 @@ public interface JakartaAuthenticationHandler {
* @throws IOException If an error occurs asking the client to drop any
* authentication traces.
*/
- void dropCredentials(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException;
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationInfoPostProcessor.java b/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationInfoPostProcessor.java
index d81a3c6..e988166 100644
--- a/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationInfoPostProcessor.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/JakartaAuthenticationInfoPostProcessor.java
@@ -1,24 +1,25 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.spi;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.SlingException;
import org.apache.sling.api.resource.LoginException;
import org.osgi.annotation.versioning.ConsumerType;
@@ -59,6 +60,5 @@ public interface JakartaAuthenticationInfoPostProcessor {
* credentials
*/
void postProcess(AuthenticationInfo info, HttpServletRequest request, HttpServletResponse response)
- throws LoginException;
-
+ throws LoginException;
}
diff --git a/src/main/java/org/apache/sling/auth/core/spi/package-info.java b/src/main/java/org/apache/sling/auth/core/spi/package-info.java
index 5c09661..5b1bae8 100755
--- a/src/main/java/org/apache/sling/auth/core/spi/package-info.java
+++ b/src/main/java/org/apache/sling/auth/core/spi/package-info.java
@@ -30,5 +30,3 @@
*/
@org.osgi.annotation.versioning.Version("1.3.0")
package org.apache.sling.auth.core.spi;
-
-
diff --git a/src/main/java/org/apache/sling/engine/auth/AuthenticationHandler.java b/src/main/java/org/apache/sling/engine/auth/AuthenticationHandler.java
index d3da576..31fa81f 100644
--- a/src/main/java/org/apache/sling/engine/auth/AuthenticationHandler.java
+++ b/src/main/java/org/apache/sling/engine/auth/AuthenticationHandler.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.engine.auth;
-import java.io.IOException;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
/**
* The <code>AuthenticationHandler</code> interface defines the service API used
* by the authentication implementation to support plugin various ways of
@@ -89,8 +89,7 @@ public interface AuthenticationHandler {
* In case of {@link AuthenticationInfo#DOING_AUTH}, the method must
* have sent a response indicating that fact to the client.
*/
- AuthenticationInfo authenticate(HttpServletRequest request,
- HttpServletResponse response);
+ AuthenticationInfo authenticate(HttpServletRequest request, HttpServletResponse response);
/**
* Requests authentication information from the client. Returns
@@ -114,6 +113,5 @@ public interface AuthenticationHandler {
* @throws IOException If an error occurrs sending the authentication
* inquiry to the client.
*/
- boolean requestAuthentication(HttpServletRequest request,
- HttpServletResponse response) throws IOException;
+ boolean requestAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException;
}
diff --git a/src/main/java/org/apache/sling/engine/auth/AuthenticationInfo.java b/src/main/java/org/apache/sling/engine/auth/AuthenticationInfo.java
index 3e33733..6757ba0 100644
--- a/src/main/java/org/apache/sling/engine/auth/AuthenticationInfo.java
+++ b/src/main/java/org/apache/sling/engine/auth/AuthenticationInfo.java
@@ -80,8 +80,7 @@ public class AuthenticationInfo {
* @see #getAuthType()
* @see #getCredentials()
*/
- public AuthenticationInfo(String authType, Credentials credentials,
- String workspaceName) {
+ public AuthenticationInfo(String authType, Credentials credentials, String workspaceName) {
this.authType = authType;
this.credentials = credentials;
this.workspaceName = workspaceName;
diff --git a/src/main/java/org/apache/sling/engine/auth/Authenticator.java b/src/main/java/org/apache/sling/engine/auth/Authenticator.java
index 81e6c75..dd8290f 100644
--- a/src/main/java/org/apache/sling/engine/auth/Authenticator.java
+++ b/src/main/java/org/apache/sling/engine/auth/Authenticator.java
@@ -60,5 +60,4 @@ public interface Authenticator {
* @throws IllegalStateException If the response has already been committed.
*/
public void login(HttpServletRequest request, HttpServletResponse response);
-
}
diff --git a/src/main/java/org/apache/sling/engine/auth/NoAuthenticationHandlerException.java b/src/main/java/org/apache/sling/engine/auth/NoAuthenticationHandlerException.java
index a85c273..f3d6eb6 100644
--- a/src/main/java/org/apache/sling/engine/auth/NoAuthenticationHandlerException.java
+++ b/src/main/java/org/apache/sling/engine/auth/NoAuthenticationHandlerException.java
@@ -41,5 +41,4 @@ public class NoAuthenticationHandlerException extends SlingException {
public NoAuthenticationHandlerException() {
super();
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/auth/package-info.java b/src/main/java/org/apache/sling/engine/auth/package-info.java
index 22743cf..755ef98 100755
--- a/src/main/java/org/apache/sling/engine/auth/package-info.java
+++ b/src/main/java/org/apache/sling/engine/auth/package-info.java
@@ -30,5 +30,3 @@
*/
@org.osgi.annotation.versioning.Version("2.0.6")
package org.apache.sling.engine.auth;
-
-
diff --git a/src/test/java/org/apache/sling/auth/core/AuthUtilTest.java b/src/test/java/org/apache/sling/auth/core/AuthUtilTest.java
index f3ba07b..6d9de6a 100644
--- a/src/test/java/org/apache/sling/auth/core/AuthUtilTest.java
+++ b/src/test/java/org/apache/sling/auth/core/AuthUtilTest.java
@@ -19,7 +19,6 @@
package org.apache.sling.auth.core;
import jakarta.servlet.http.HttpServletRequest;
-
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.SyntheticResource;
@@ -29,25 +28,25 @@ import org.mockito.Mockito;
public class AuthUtilTest {
- final ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
+ final ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
@Test
public void test_isRedirectValid_null_empty() {
- Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest)null, null));
- Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest)null, ""));
+ Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest) null, null));
+ Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest) null, ""));
}
@Test
public void test_isRedirectValid_url() {
- Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest)null, "http://www.google.com"));
+ Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest) null, "http://www.google.com"));
}
@Test
public void test_isRedirectValid_no_request() {
- Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest)null, "relative/path"));
- Assert.assertTrue(AuthUtil.isRedirectValid((HttpServletRequest)null, "/absolute/path"));
+ Assert.assertFalse(AuthUtil.isRedirectValid((HttpServletRequest) null, "relative/path"));
+ Assert.assertTrue(AuthUtil.isRedirectValid((HttpServletRequest) null, "/absolute/path"));
}
@Test
@@ -98,14 +97,15 @@ public class AuthUtilTest {
@Test
public void test_isRedirectValid_resource_resolver_root_context() {
Mockito.when(request.getContextPath()).thenReturn("");
- Mockito.when(request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER)).thenReturn(resolver);
+ Mockito.when(request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER))
+ .thenReturn(resolver);
- Mockito.when(resolver.resolve((HttpServletRequest)Mockito.any(), Mockito.eq("/absolute/path")))
- .thenReturn(new SyntheticResource(resolver, "/absolute/path", "test"));
- Mockito.when(resolver.resolve((HttpServletRequest)Mockito.any(), Mockito.eq("relative/path")))
- .thenReturn(new NonExistingResource(resolver, "relative/path"));
- Mockito.when(resolver.resolve((HttpServletRequest)Mockito.any(), Mockito.any()))
- .thenReturn(new NonExistingResource(resolver, "/absolute/missing"));
+ Mockito.when(resolver.resolve((HttpServletRequest) Mockito.any(), Mockito.eq("/absolute/path")))
+ .thenReturn(new SyntheticResource(resolver, "/absolute/path", "test"));
+ Mockito.when(resolver.resolve((HttpServletRequest) Mockito.any(), Mockito.eq("relative/path")))
+ .thenReturn(new NonExistingResource(resolver, "relative/path"));
+ Mockito.when(resolver.resolve((HttpServletRequest) Mockito.any(), Mockito.any()))
+ .thenReturn(new NonExistingResource(resolver, "/absolute/missing"));
Assert.assertFalse(AuthUtil.isRedirectValid(request, "relative/path"));
Assert.assertTrue(AuthUtil.isRedirectValid(request, "/absolute/path"));
@@ -121,14 +121,15 @@ public class AuthUtilTest {
@Test
public void test_isRedirectValid_resource_resolver_non_root_context() {
Mockito.when(request.getContextPath()).thenReturn("/ctx");
- Mockito.when(request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER)).thenReturn(resolver);
-
- Mockito.when(resolver.resolve((HttpServletRequest)Mockito.any(), Mockito.eq("/absolute/path")))
- .thenReturn(new SyntheticResource(resolver, "/absolute/path", "test"));
- Mockito.when(resolver.resolve((HttpServletRequest)Mockito.any(), Mockito.eq("relative/path")))
- .thenReturn(new NonExistingResource(resolver, "relative/path"));
- Mockito.when(resolver.resolve((HttpServletRequest)Mockito.any(), Mockito.any()))
- .thenReturn(new NonExistingResource(resolver, "/absolute/missing"));
+ Mockito.when(request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER))
+ .thenReturn(resolver);
+
+ Mockito.when(resolver.resolve((HttpServletRequest) Mockito.any(), Mockito.eq("/absolute/path")))
+ .thenReturn(new SyntheticResource(resolver, "/absolute/path", "test"));
+ Mockito.when(resolver.resolve((HttpServletRequest) Mockito.any(), Mockito.eq("relative/path")))
+ .thenReturn(new NonExistingResource(resolver, "relative/path"));
+ Mockito.when(resolver.resolve((HttpServletRequest) Mockito.any(), Mockito.any()))
+ .thenReturn(new NonExistingResource(resolver, "/absolute/missing"));
Assert.assertFalse(AuthUtil.isRedirectValid(request, "relative/path"));
Assert.assertFalse(AuthUtil.isRedirectValid(request, "/absolute/path"));
diff --git a/src/test/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManagerTest.java b/src/test/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManagerTest.java
index 14c3450..65cba5e 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManagerTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/AuthenticationHandlersManagerTest.java
@@ -18,27 +18,28 @@
*/
package org.apache.sling.auth.core.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import junitx.util.PrivateAccessor;
import org.apache.sling.auth.core.spi.AuthenticationHandler;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
-import junitx.util.PrivateAccessor;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
public class AuthenticationHandlersManagerTest {
- @Test public void testDefaultConfiguration() {
- final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(SlingAuthenticatorTest.createDefaultConfig());
+ @Test
+ public void testDefaultConfiguration() {
+ final AuthenticationHandlersManager manager =
+ new AuthenticationHandlersManager(SlingAuthenticatorTest.createDefaultConfig());
final Map<String, List<String>> map = manager.getAuthenticationHandlerMap();
assertEquals(1, map.size());
@@ -48,7 +49,8 @@ public class AuthenticationHandlersManagerTest {
assertEquals("HTTP Basic Authentication Handler (preemptive)", list.get(0));
}
- @Test public void testDefaultConfigurationDisabled() {
+ @Test
+ public void testDefaultConfigurationDisabled() {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
@@ -57,7 +59,8 @@ public class AuthenticationHandlersManagerTest {
assertTrue(map.isEmpty());
}
- @Test public void testDefaultConfigurationEnabled() {
+ @Test
+ public void testDefaultConfigurationEnabled() {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_ENABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
@@ -70,23 +73,24 @@ public class AuthenticationHandlersManagerTest {
assertEquals("HTTP Basic Authentication Handler (enabled)", list.get(0));
}
- private void assertPaths(final PathBasedHolderCache<AbstractAuthenticationHandlerHolder> cache,
+ private void assertPaths(
+ final PathBasedHolderCache<AbstractAuthenticationHandlerHolder> cache,
final String[] paths,
final ServiceReference<?>[] refs) {
assertEquals("Wrong input to assert paths", paths.length, refs.length);
- for(final AbstractAuthenticationHandlerHolder h : cache.getHolders()) {
- int index = 0 ;
+ for (final AbstractAuthenticationHandlerHolder h : cache.getHolders()) {
+ int index = 0;
boolean found = false;
- while ( !found && index < paths.length ) {
- if (paths[index].equals(h.path) && refs[index].equals(h.serviceReference) ) {
+ while (!found && index < paths.length) {
+ if (paths[index].equals(h.path) && refs[index].equals(h.serviceReference)) {
found = true;
} else {
index++;
}
}
- assertTrue(Arrays.toString(paths) + " should contain " + h.path, found);
+ assertTrue(Arrays.toString(paths) + " should contain " + h.path, found);
}
}
@@ -97,12 +101,13 @@ public class AuthenticationHandlersManagerTest {
@SuppressWarnings("deprecation")
private ServiceReference<?> createServiceReference(final String[] paths) {
final ServiceReference<?> ref = mock(ServiceReference.class);
- when(ref.getProperty(org.apache.sling.engine.auth.AuthenticationHandler.PATH_PROPERTY)).thenReturn(paths);
+ when(ref.getProperty(org.apache.sling.engine.auth.AuthenticationHandler.PATH_PROPERTY))
+ .thenReturn(paths);
when(ref.getProperty(AuthenticationHandler.PATH_PROPERTY)).thenReturn(paths);
when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(serviceId);
serviceId++;
- for(final ServiceReference<?> r : refs) {
+ for (final ServiceReference<?> r : refs) {
when(ref.compareTo(r)).thenReturn(1);
when(r.compareTo(ref)).thenReturn(-1);
}
@@ -112,7 +117,8 @@ public class AuthenticationHandlersManagerTest {
return ref;
}
- @Test public void testAddRemoveRegistration() throws Throwable {
+ @Test
+ public void testAddRemoveRegistration() throws Throwable {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
@@ -120,19 +126,21 @@ public class AuthenticationHandlersManagerTest {
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1"});
final AuthenticationHandler handler = mock(AuthenticationHandler.class);
- PrivateAccessor.invoke(manager, "bindAuthHandler",
- new Class[]{AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref});
+ PrivateAccessor.invoke(
+ manager,
+ "bindAuthHandler",
+ new Class[] {AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref});
- assertPaths(manager, new String[] {"/path1"},
- new ServiceReference<?>[] {ref});
+ assertPaths(manager, new String[] {"/path1"}, new ServiceReference<?>[] {ref});
- PrivateAccessor.invoke(manager, "unbindAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref});
+ PrivateAccessor.invoke(manager, "unbindAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref});
assertTrue(manager.getHolders().isEmpty());
}
- @Test public void testAddUpdateRemoveRegistration() throws Throwable {
+ @Test
+ public void testAddUpdateRemoveRegistration() throws Throwable {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
@@ -141,28 +149,32 @@ public class AuthenticationHandlersManagerTest {
final AuthenticationHandler handler = mock(AuthenticationHandler.class);
// add
- PrivateAccessor.invoke(manager, "bindAuthHandler",
- new Class[]{AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref});
+ PrivateAccessor.invoke(
+ manager,
+ "bindAuthHandler",
+ new Class[] {AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref});
- assertPaths(manager, new String[] {"/path1", "/path2"},
- new ServiceReference<?>[] {ref, ref});
+ assertPaths(manager, new String[] {"/path1", "/path2"}, new ServiceReference<?>[] {ref, ref});
// update
when(ref.getProperty(AuthenticationHandler.PATH_PROPERTY)).thenReturn(new String[] {"/path2", "/path3"});
- PrivateAccessor.invoke(manager, "updatedAuthHandler",
- new Class[]{AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref});
+ PrivateAccessor.invoke(
+ manager,
+ "updatedAuthHandler",
+ new Class[] {AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref});
- assertPaths(manager, new String[] {"/path2", "/path3"},
- new ServiceReference<?>[] {ref, ref});
+ assertPaths(manager, new String[] {"/path2", "/path3"}, new ServiceReference<?>[] {ref, ref});
// remmove
- PrivateAccessor.invoke(manager, "unbindAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref});
+ PrivateAccessor.invoke(manager, "unbindAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref});
assertTrue(manager.getHolders().isEmpty());
}
- @Test public void testDuplicateRegistration() throws Throwable {
+ @Test
+ public void testDuplicateRegistration() throws Throwable {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
@@ -172,108 +184,130 @@ public class AuthenticationHandlersManagerTest {
// add
final ServiceReference<?> ref1 = createServiceReference(new String[] {"/path1", "/path1", "/path2"});
// add
- PrivateAccessor.invoke(manager, "bindAuthHandler",
- new Class[]{AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref1});
+ PrivateAccessor.invoke(
+ manager,
+ "bindAuthHandler",
+ new Class[] {AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref1});
final ServiceReference<?> ref2 = createServiceReference(new String[] {"/path2", "/path3"});
// add
- PrivateAccessor.invoke(manager, "bindAuthHandler",
- new Class[]{AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref2});
- assertPaths(manager, new String[] {"/path1", "/path2", "/path2", "/path3"},
- new ServiceReference<?>[] {ref1, ref1, ref2, ref2});
+ PrivateAccessor.invoke(
+ manager,
+ "bindAuthHandler",
+ new Class[] {AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref2});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path2", "/path3"}, new ServiceReference<?>[] {
+ ref1, ref1, ref2, ref2
+ });
- PrivateAccessor.invoke(manager, "unbindAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref2});
+ PrivateAccessor.invoke(manager, "unbindAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref2});
- assertPaths(manager, new String[] {"/path1", "/path2"},
- new ServiceReference<?>[] {ref1, ref1});
+ assertPaths(manager, new String[] {"/path1", "/path2"}, new ServiceReference<?>[] {ref1, ref1});
- PrivateAccessor.invoke(manager, "unbindAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref1});
+ PrivateAccessor.invoke(manager, "unbindAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref1});
assertTrue(manager.getHolders().isEmpty());
}
@Deprecated
- @Test public void testAddRemoveRegistrationLegacy() throws Throwable {
+ @Test
+ public void testAddRemoveRegistrationLegacy() throws Throwable {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1"});
- final org.apache.sling.engine.auth.AuthenticationHandler handler = mock(org.apache.sling.engine.auth.AuthenticationHandler.class);
+ final org.apache.sling.engine.auth.AuthenticationHandler handler =
+ mock(org.apache.sling.engine.auth.AuthenticationHandler.class);
- PrivateAccessor.invoke(manager, "bindEngineAuthHandler",
- new Class[]{org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref});
+ PrivateAccessor.invoke(
+ manager,
+ "bindEngineAuthHandler",
+ new Class[] {org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref});
- assertPaths(manager, new String[] {"/path1"},
- new ServiceReference<?>[] {ref});
+ assertPaths(manager, new String[] {"/path1"}, new ServiceReference<?>[] {ref});
- PrivateAccessor.invoke(manager, "unbindEngineAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref});
+ PrivateAccessor.invoke(
+ manager, "unbindEngineAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref});
assertTrue(manager.getHolders().isEmpty());
}
@Deprecated
- @Test public void testAddUpdateRemoveRegistrationLegacy() throws Throwable {
+ @Test
+ public void testAddUpdateRemoveRegistrationLegacy() throws Throwable {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1", "/path2"});
- final org.apache.sling.engine.auth.AuthenticationHandler handler = mock(org.apache.sling.engine.auth.AuthenticationHandler.class);
+ final org.apache.sling.engine.auth.AuthenticationHandler handler =
+ mock(org.apache.sling.engine.auth.AuthenticationHandler.class);
// add
- PrivateAccessor.invoke(manager, "bindEngineAuthHandler",
- new Class[]{org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref});
+ PrivateAccessor.invoke(
+ manager,
+ "bindEngineAuthHandler",
+ new Class[] {org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref});
- assertPaths(manager, new String[] {"/path1", "/path2"},
- new ServiceReference<?>[] {ref, ref});
+ assertPaths(manager, new String[] {"/path1", "/path2"}, new ServiceReference<?>[] {ref, ref});
// update
when(ref.getProperty(AuthenticationHandler.PATH_PROPERTY)).thenReturn(new String[] {"/path2", "/path3"});
- PrivateAccessor.invoke(manager, "updatedEngineAuthHandler",
- new Class[]{org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref});
+ PrivateAccessor.invoke(
+ manager,
+ "updatedEngineAuthHandler",
+ new Class[] {org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref});
- assertPaths(manager, new String[] {"/path2", "/path3"},
- new ServiceReference<?>[] {ref, ref});
+ assertPaths(manager, new String[] {"/path2", "/path3"}, new ServiceReference<?>[] {ref, ref});
// remmove
- PrivateAccessor.invoke(manager, "unbindEngineAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref});
+ PrivateAccessor.invoke(
+ manager, "unbindEngineAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref});
assertTrue(manager.getHolders().isEmpty());
}
@Deprecated
- @Test public void testDuplicateRegistrationLegacy() throws Throwable {
+ @Test
+ public void testDuplicateRegistrationLegacy() throws Throwable {
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
when(config.auth_http()).thenReturn(SlingAuthenticator.HTTP_AUTH_DISABLED);
final AuthenticationHandlersManager manager = new AuthenticationHandlersManager(config);
- final org.apache.sling.engine.auth.AuthenticationHandler handler = mock(org.apache.sling.engine.auth.AuthenticationHandler.class);
+ final org.apache.sling.engine.auth.AuthenticationHandler handler =
+ mock(org.apache.sling.engine.auth.AuthenticationHandler.class);
// add
final ServiceReference<?> ref1 = createServiceReference(new String[] {"/path1", "/path1", "/path2"});
// add
- PrivateAccessor.invoke(manager, "bindEngineAuthHandler",
- new Class[]{org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref1});
+ PrivateAccessor.invoke(
+ manager,
+ "bindEngineAuthHandler",
+ new Class[] {org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref1});
final ServiceReference<?> ref2 = createServiceReference(new String[] {"/path2", "/path3"});
// add
- PrivateAccessor.invoke(manager, "bindEngineAuthHandler",
- new Class[]{org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class}, new Object[]{handler, ref2});
- assertPaths(manager, new String[] {"/path1", "/path2", "/path2", "/path3"},
- new ServiceReference<?>[] {ref1, ref1, ref2, ref2});
-
- PrivateAccessor.invoke(manager, "unbindEngineAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref2});
-
- assertPaths(manager, new String[] {"/path1", "/path2"},
- new ServiceReference<?>[] {ref1, ref1});
-
- PrivateAccessor.invoke(manager, "unbindEngineAuthHandler",
- new Class[]{ServiceReference.class}, new Object[]{ref1});
+ PrivateAccessor.invoke(
+ manager,
+ "bindEngineAuthHandler",
+ new Class[] {org.apache.sling.engine.auth.AuthenticationHandler.class, ServiceReference.class},
+ new Object[] {handler, ref2});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path2", "/path3"}, new ServiceReference<?>[] {
+ ref1, ref1, ref2, ref2
+ });
+
+ PrivateAccessor.invoke(
+ manager, "unbindEngineAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref2});
+
+ assertPaths(manager, new String[] {"/path1", "/path2"}, new ServiceReference<?>[] {ref1, ref1});
+
+ PrivateAccessor.invoke(
+ manager, "unbindEngineAuthHandler", new Class[] {ServiceReference.class}, new Object[] {ref1});
assertTrue(manager.getHolders().isEmpty());
}
}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManagerTest.java b/src/test/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManagerTest.java
index 86ca1af..1ed6be7 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManagerTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/AuthenticationRequirementsManagerTest.java
@@ -18,11 +18,6 @@
*/
package org.apache.sling.auth.core.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -40,34 +35,44 @@ import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
public class AuthenticationRequirementsManagerTest {
- private void assertPaths(final PathBasedHolderCache<AuthenticationRequirementHolder> cache,
+ private void assertPaths(
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache,
final String[] paths,
final ServiceReference<?>[] refs) {
assertPaths(cache, paths, refs, null);
}
- private void assertPaths(final PathBasedHolderCache<AuthenticationRequirementHolder> cache,
+ private void assertPaths(
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache,
final String[] paths,
final ServiceReference<?>[] refs,
final boolean[] requireAuth) {
assertEquals("Wrong input to assert paths", paths.length, refs.length);
- if ( requireAuth != null ) {
+ if (requireAuth != null) {
assertEquals("Wrong input to assert paths", paths.length, requireAuth.length);
}
// there are three default entries
assertEquals(3 + paths.length, cache.getHolders().size());
- for(final AuthenticationRequirementHolder h : cache.getHolders()) {
- boolean found = Arrays.asList(LoginServlet.SERVLET_PATH, LogoutServlet.SERVLET_PATH, "/").contains(h.path);
- if ( !found ) {
- int index = 0 ;
- while ( !found && index < paths.length ) {
- if (paths[index].equals(h.path) && ((refs[index] == null && h.serviceReference == null) || refs[index].equals(h.serviceReference)) ) {
+ for (final AuthenticationRequirementHolder h : cache.getHolders()) {
+ boolean found = Arrays.asList(LoginServlet.SERVLET_PATH, LogoutServlet.SERVLET_PATH, "/")
+ .contains(h.path);
+ if (!found) {
+ int index = 0;
+ while (!found && index < paths.length) {
+ if (paths[index].equals(h.path)
+ && ((refs[index] == null && h.serviceReference == null)
+ || refs[index].equals(h.serviceReference))) {
found = true;
-
- if ( requireAuth != null ) {
+
+ if (requireAuth != null) {
assertEquals(requireAuth[index], h.requiresAuthentication());
}
} else {
@@ -75,7 +80,7 @@ public class AuthenticationRequirementsManagerTest {
}
}
}
- assertTrue(Arrays.toString(paths) + " should contain " + h.path, found);
+ assertTrue(Arrays.toString(paths) + " should contain " + h.path, found);
}
}
@@ -89,7 +94,7 @@ public class AuthenticationRequirementsManagerTest {
when(ref.getProperty(Constants.SERVICE_ID)).thenReturn(serviceId);
serviceId++;
- for(final ServiceReference<?> r : refs) {
+ for (final ServiceReference<?> r : refs) {
when(ref.compareTo(r)).thenReturn(1);
when(r.compareTo(ref)).thenReturn(-1);
}
@@ -98,7 +103,7 @@ public class AuthenticationRequirementsManagerTest {
final Bundle bundle = mock(Bundle.class);
when(bundle.getBundleId()).thenReturn(1L);
when(ref.getBundle()).thenReturn(bundle);
-
+
refs.add(ref);
return ref;
}
@@ -124,50 +129,61 @@ public class AuthenticationRequirementsManagerTest {
when(context.getBundle()).thenReturn(bundle);
return context;
}
-
- @Test public void testAddRemoveRegistration() throws LoginException {
+
+ @Test
+ public void testAddRemoveRegistration() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
assertEquals(3, manager.getHolders().size());
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1"},
- new ServiceReference<?>[] {ref});
+ assertPaths(manager, new String[] {"/path1"}, new ServiceReference<?>[] {ref});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
assertEquals(3, manager.getHolders().size());
}
- @Test public void testAddUpdateRemoveRegistration() throws LoginException {
+ @Test
+ public void testAddUpdateRemoveRegistration() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path1a"));
when(mapper.getAllMappings("/path2")).thenReturn(Arrays.asList("/path2", "/path2a"));
when(mapper.getAllMappings("/path3")).thenReturn(Arrays.asList("/path3", "/path3a"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
// add
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1", "/path2"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1", "/path1a", "/path2", "/path2a"},
- new ServiceReference<?>[] {ref, ref, ref, ref},
- new boolean[] {true, true, true, true});
+ assertPaths(
+ manager,
+ new String[] {"/path1", "/path1a", "/path2", "/path2a"},
+ new ServiceReference<?>[] {ref, ref, ref, ref},
+ new boolean[] {true, true, true, true});
// update
when(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS)).thenReturn(new String[] {"/path2", "/path3"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref));
- assertPaths(manager, new String[] {"/path2", "/path2a", "/path3", "/path3a"},
+ assertPaths(
+ manager,
+ new String[] {"/path2", "/path2a", "/path3", "/path3a"},
new ServiceReference<?>[] {ref, ref, ref, ref},
new boolean[] {true, true, true, true});
@@ -177,33 +193,38 @@ public class AuthenticationRequirementsManagerTest {
assertEquals(3, manager.getHolders().size());
}
- @Test public void testDuplicateRegistration() throws LoginException {
+ @Test
+ public void testDuplicateRegistration() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
when(mapper.getAllMappings("/path2")).thenReturn(Collections.singleton("/path2"));
when(mapper.getAllMappings("/path3")).thenReturn(Collections.singleton("/path3"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref1 = createServiceReference(new String[] {"/path1", "/path1", "/path2"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref1));
final ServiceReference<?> ref2 = createServiceReference(new String[] {"/path2", "/path3"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref2));
- assertPaths(manager, new String[] {"/path1", "/path2", "/path2", "/path3"},
- new ServiceReference<?>[] {ref1, ref1, ref2, ref2});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path2", "/path3"}, new ServiceReference<?>[] {
+ ref1, ref1, ref2, ref2
+ });
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref2));
- assertPaths(manager, new String[] {"/path1", "/path2"},
- new ServiceReference<?>[] {ref1, ref1});
+ assertPaths(manager, new String[] {"/path1", "/path2"}, new ServiceReference<?>[] {ref1, ref1});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref1));
assertEquals(3, manager.getHolders().size());
}
- @Test public void testAddRemoveRegistrations() throws LoginException {
+ @Test
+ public void testAddRemoveRegistrations() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
@@ -211,8 +232,11 @@ public class AuthenticationRequirementsManagerTest {
when(mapper.getAllMappings("/path3")).thenReturn(Collections.singleton("/path3"));
when(mapper.getAllMappings("/path4")).thenReturn(Collections.singleton("/path4"));
when(mapper.getAllMappings("/path5")).thenReturn(Collections.singleton("/path5"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref1 = createServiceReference(new String[] {"/path1"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref1));
@@ -223,23 +247,24 @@ public class AuthenticationRequirementsManagerTest {
final ServiceReference<?> ref3 = createServiceReference(new String[] {"/path4", "/path5"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref3));
- assertPaths(manager, new String[] { "/path1", "/path2", "/path3", "/path4", "/path5"},
- new ServiceReference<?>[] {ref1, ref2, ref2, ref3, ref3});
+ assertPaths(
+ manager,
+ new String[] {"/path1", "/path2", "/path3", "/path4", "/path5"},
+ new ServiceReference<?>[] {ref1, ref2, ref2, ref3, ref3});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref2));
- assertPaths(manager, new String[] { "/path1", "/path4", "/path5"},
- new ServiceReference<?>[] {ref1, ref3, ref3});
+ assertPaths(manager, new String[] {"/path1", "/path4", "/path5"}, new ServiceReference<?>[] {ref1, ref3, ref3});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref1));
- assertPaths(manager, new String[] { "/path4", "/path5"},
- new ServiceReference<?>[] {ref3, ref3});
+ assertPaths(manager, new String[] {"/path4", "/path5"}, new ServiceReference<?>[] {ref3, ref3});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref3));
assertEquals(3, manager.getHolders().size());
}
- @Test public void testModifyRegistration() throws LoginException {
+ @Test
+ public void testModifyRegistration() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
@@ -247,63 +272,68 @@ public class AuthenticationRequirementsManagerTest {
when(mapper.getAllMappings("/path3")).thenReturn(Collections.singleton("/path3"));
when(mapper.getAllMappings("/path4")).thenReturn(Collections.singleton("/path4"));
when(mapper.getAllMappings("/path5")).thenReturn(Collections.singleton("/path5"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref1 = createServiceReference(new String[] {"/path1", "/path2", "/path3"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref1));
- assertPaths(manager, new String[] { "/path1", "/path2", "/path3"},
- new ServiceReference<?>[] {ref1, ref1, ref1});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path3"}, new ServiceReference<?>[] {ref1, ref1, ref1});
when(ref1.getProperty(AuthConstants.AUTH_REQUIREMENTS)).thenReturn(new String[] {"/path1", "/path4", "/path5"});
- assertPaths(manager, new String[] { "/path1", "/path2", "/path3"},
- new ServiceReference<?>[] {ref1, ref1, ref1});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path3"}, new ServiceReference<?>[] {ref1, ref1, ref1});
manager.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref1));
- assertPaths(manager, new String[] { "/path1", "/path4", "/path5"},
- new ServiceReference<?>[] {ref1, ref1, ref1});
+ assertPaths(manager, new String[] {"/path1", "/path4", "/path5"}, new ServiceReference<?>[] {ref1, ref1, ref1});
manager.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED_ENDMATCH, ref1));
assertEquals(3, manager.getHolders().size());
}
- @Test public void testRegistrationWithMapping() throws LoginException {
+ @Test
+ public void testRegistrationWithMapping() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path2", "/path3"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1", "/path2", "/path3"},
- new ServiceReference<?>[] {ref, ref, ref});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path3"}, new ServiceReference<?>[] {ref, ref, ref});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
assertEquals(3, manager.getHolders().size());
}
- @Test public void testRegistrationAndUpdatingMapping() throws LoginException {
+ @Test
+ public void testRegistrationAndUpdatingMapping() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path2", "/path3"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1", "/path2", "/path3"},
- new ServiceReference<?>[] {ref, ref, ref});
+ assertPaths(manager, new String[] {"/path1", "/path2", "/path3"}, new ServiceReference<?>[] {ref, ref, ref});
// update mapper
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path5"));
manager.handleEvent(null);
- assertPaths(manager, new String[] {"/path1", "/path5"},
- new ServiceReference<?>[] {ref, ref});
+ assertPaths(manager, new String[] {"/path1", "/path5"}, new ServiceReference<?>[] {ref, ref});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
@@ -311,71 +341,85 @@ public class AuthenticationRequirementsManagerTest {
}
// see SLING-11867
- @Test public void testRegistrationWithEmptyMapping() throws LoginException {
+ @Test
+ public void testRegistrationWithEmptyMapping() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
// Resourcemapper returns empty mapping
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", ""));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
// register
final ServiceReference<?> ref = createServiceReference(new String[] {"+/path1"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
// empty path "" returned by resourcemapper should have been ignored
- assertPaths(manager, new String[] {"/path1"},
- new ServiceReference<?>[] {ref},
- new boolean[] {true});
+ assertPaths(manager, new String[] {"/path1"}, new ServiceReference<?>[] {ref}, new boolean[] {true});
// update mapper
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path5"));
manager.handleEvent(null);
- assertPaths(manager, new String[] {"/path1", "/path5"},
- new ServiceReference<?>[] {ref, ref},
- new boolean[] {true, true});
+ assertPaths(manager, new String[] {"/path1", "/path5"}, new ServiceReference<?>[] {ref, ref}, new boolean[] {
+ true, true
+ });
// update mapper - now again with empty mapping to test the case of modified
// empty "" should be ignored
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", ""));
manager.handleEvent(null);
- assertPaths(manager, new String[] {"/path1"},
- new ServiceReference<?>[] {ref},
- new boolean[] {true});
+ assertPaths(manager, new String[] {"/path1"}, new ServiceReference<?>[] {ref}, new boolean[] {true});
}
- @Test public void testAllowDeny() throws LoginException {
+ @Test
+ public void testAllowDeny() throws LoginException {
final BundleContext context = createBundleContext();
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(null),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(null),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref = createServiceReference(new String[] {"-/path1", "+/path2", "/path3"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1", "/path2", "/path3"},
- new ServiceReference<?>[] {ref, ref, ref},
- new boolean[] {false, true, true});
+ assertPaths(
+ manager,
+ new String[] {"/path1", "/path2", "/path3"},
+ new ServiceReference<?>[] {ref, ref, ref},
+ new boolean[] {false, true, true});
}
- @Test public void testAllowDenyWithMapping() throws LoginException {
+ @Test
+ public void testAllowDenyWithMapping() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path1a", "/path1b"));
when(mapper.getAllMappings("/path2")).thenReturn(Arrays.asList("/path2", "/path2a", "/path2b"));
when(mapper.getAllMappings("/path3")).thenReturn(Arrays.asList("/path3", "/path3a", "/path3b"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
final ServiceReference<?> ref = createServiceReference(new String[] {"-/path1", "+/path2", "/path3"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1", "/path2", "/path3", "/path1a", "/path2a", "/path3a", "/path1b", "/path2b", "/path3b"},
- new ServiceReference<?>[] {ref, ref, ref, ref, ref, ref, ref, ref, ref},
- new boolean[] {false, true, true, false, true, true, false, true, true});
+ assertPaths(
+ manager,
+ new String[] {
+ "/path1", "/path2", "/path3", "/path1a", "/path2a", "/path3a", "/path1b", "/path2b", "/path3b"
+ },
+ new ServiceReference<?>[] {ref, ref, ref, ref, ref, ref, ref, ref, ref},
+ new boolean[] {false, true, true, false, true, true, false, true, true});
// update mapping
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path1c"));
@@ -383,33 +427,43 @@ public class AuthenticationRequirementsManagerTest {
when(mapper.getAllMappings("/path3")).thenReturn(Arrays.asList("/path3", "/path3c"));
manager.handleEvent(null);
- assertPaths(manager, new String[] {"/path1", "/path2", "/path3", "/path1c", "/path2c", "/path3c"},
+ assertPaths(
+ manager,
+ new String[] {"/path1", "/path2", "/path3", "/path1c", "/path2c", "/path3c"},
new ServiceReference<?>[] {ref, ref, ref, ref, ref, ref},
new boolean[] {false, true, true, false, true, true});
}
- @Test public void testSwitchAllowDeny() throws LoginException {
+ @Test
+ public void testSwitchAllowDeny() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1", "/path1a"));
when(mapper.getAllMappings("/path2")).thenReturn(Arrays.asList("/path2", "/path2a"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
// add
final ServiceReference<?> ref = createServiceReference(new String[] {"+/path1", "-/path2"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- assertPaths(manager, new String[] {"/path1", "/path1a", "/path2", "/path2a"},
- new ServiceReference<?>[] {ref, ref, ref, ref},
- new boolean[] {true, true, false, false});
+ assertPaths(
+ manager,
+ new String[] {"/path1", "/path1a", "/path2", "/path2a"},
+ new ServiceReference<?>[] {ref, ref, ref, ref},
+ new boolean[] {true, true, false, false});
// update
when(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS)).thenReturn(new String[] {"-/path1", "/path2"});
manager.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref));
- assertPaths(manager, new String[] {"/path1", "/path1a", "/path2", "/path2a"},
+ assertPaths(
+ manager,
+ new String[] {"/path1", "/path1a", "/path2", "/path2a"},
new ServiceReference<?>[] {ref, ref, ref, ref},
new boolean[] {false, false, true, true});
@@ -419,12 +473,16 @@ public class AuthenticationRequirementsManagerTest {
assertEquals(3, manager.getHolders().size());
}
- @Test public void testIgnoreRegistrationFromAuthCoreBundle() throws LoginException {
+ @Test
+ public void testIgnoreRegistrationFromAuthCoreBundle() throws LoginException {
final BundleContext context = createBundleContext();
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
assertEquals(3, manager.getHolders().size());
@@ -439,28 +497,33 @@ public class AuthenticationRequirementsManagerTest {
assertEquals(3, manager.getHolders().size());
}
- @Test public void testInitialServices() throws Exception {
+ @Test
+ public void testInitialServices() throws Exception {
final BundleContext context = createBundleContext();
final ServiceReference<?> ref = createServiceReference(new String[] {"/path1"});
- when(context.getAllServiceReferences(null, "(".concat(AuthConstants.AUTH_REQUIREMENTS).concat("=*)")))
- .thenReturn(new ServiceReference[] {ref});
+ when(context.getAllServiceReferences(
+ null, "(".concat(AuthConstants.AUTH_REQUIREMENTS).concat("=*)")))
+ .thenReturn(new ServiceReference[] {ref});
final ResourceMapper mapper = mock(ResourceMapper.class);
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- SlingAuthenticatorTest.createDefaultConfig(), callable -> callable.run());
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context,
+ createFactoryForMapper(mapper),
+ SlingAuthenticatorTest.createDefaultConfig(),
+ callable -> callable.run());
- assertPaths(manager, new String[] {"/path1"},
- new ServiceReference<?>[] {ref});
+ assertPaths(manager, new String[] {"/path1"}, new ServiceReference<?>[] {ref});
manager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
assertEquals(3, manager.getHolders().size());
}
- @Test public void testInitialConfiguration() throws Exception {
+ @Test
+ public void testInitialConfiguration() throws Exception {
final BundleContext context = createBundleContext();
final SlingAuthenticator.Config config = SlingAuthenticatorTest.createDefaultConfig();
@@ -470,12 +533,11 @@ public class AuthenticationRequirementsManagerTest {
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
when(mapper.getAllMappings("/path2")).thenReturn(Collections.singleton("/path2"));
- final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(context, createFactoryForMapper(mapper),
- config, callable -> callable.run());
-
- assertPaths(manager, new String[] {"/path1", "/path2"},
- new ServiceReference<?>[] {null, null},
- new boolean[] {true, false});
+ final AuthenticationRequirementsManager manager = new AuthenticationRequirementsManager(
+ context, createFactoryForMapper(mapper), config, callable -> callable.run());
+ assertPaths(manager, new String[] {"/path1", "/path2"}, new ServiceReference<?>[] {null, null}, new boolean[] {
+ true, false
+ });
}
}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/FailureCodesMapperTest.java b/src/test/java/org/apache/sling/auth/core/impl/FailureCodesMapperTest.java
index ecc765e..e878857 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/FailureCodesMapperTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/FailureCodesMapperTest.java
@@ -18,8 +18,6 @@
*/
package org.apache.sling.auth.core.impl;
-import static org.apache.sling.auth.core.impl.FailureCodesMapper.getFailureReason;
-
import javax.jcr.SimpleCredentials;
import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
@@ -32,6 +30,8 @@ import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
+import static org.apache.sling.auth.core.impl.FailureCodesMapper.getFailureReason;
+
public class FailureCodesMapperTest {
private final AuthenticationInfo dummyAuthInfo = new AuthenticationInfo("dummy");
@@ -39,43 +39,43 @@ public class FailureCodesMapperTest {
@Test
public void unknown() {
MatcherAssert.assertThat(
- getFailureReason(dummyAuthInfo, new RuntimeException()),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.UNKNOWN));
+ getFailureReason(dummyAuthInfo, new RuntimeException()),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.UNKNOWN));
}
@Test
public void loginExceptionWithNoCause() {
MatcherAssert.assertThat(
- getFailureReason(dummyAuthInfo, new LoginException("Something went wrong")),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.INVALID_LOGIN));
+ getFailureReason(dummyAuthInfo, new LoginException("Something went wrong")),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.INVALID_LOGIN));
}
@Test
public void passwordExpired() {
MatcherAssert.assertThat(
- getFailureReason(dummyAuthInfo, new LoginException(new CredentialExpiredException())),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.PASSWORD_EXPIRED));
+ getFailureReason(dummyAuthInfo, new LoginException(new CredentialExpiredException())),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.PASSWORD_EXPIRED));
}
@Test
public void accountLocked() {
MatcherAssert.assertThat(
- getFailureReason(dummyAuthInfo, new LoginException(new AccountLockedException())),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.ACCOUNT_LOCKED));
+ getFailureReason(dummyAuthInfo, new LoginException(new AccountLockedException())),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.ACCOUNT_LOCKED));
}
@Test
public void accountNotFound() {
MatcherAssert.assertThat(
- getFailureReason(dummyAuthInfo, new LoginException(new AccountNotFoundException())),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.ACCOUNT_NOT_FOUND));
+ getFailureReason(dummyAuthInfo, new LoginException(new AccountNotFoundException())),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.ACCOUNT_NOT_FOUND));
}
@Test
public void expiredToken() {
MatcherAssert.assertThat(
- getFailureReason(dummyAuthInfo, new LoginException(new TokenCredentialsExpiredException())),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.EXPIRED_TOKEN));
+ getFailureReason(dummyAuthInfo, new LoginException(new TokenCredentialsExpiredException())),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.EXPIRED_TOKEN));
}
@Test
@@ -87,15 +87,13 @@ public class FailureCodesMapperTest {
info.put("user.jcr.credentials", credentials);
MatcherAssert.assertThat(
- getFailureReason(info, new LoginException(new CredentialExpiredException())),
- CoreMatchers.equalTo(FAILURE_REASON_CODES.PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY));
+ getFailureReason(info, new LoginException(new CredentialExpiredException())),
+ CoreMatchers.equalTo(FAILURE_REASON_CODES.PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY));
}
// doubles for an Oak class
static class TokenCredentialsExpiredException extends Exception {
private static final long serialVersionUID = 1L;
-
}
-
}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/PathBasedHolderTest.java b/src/test/java/org/apache/sling/auth/core/impl/PathBasedHolderTest.java
index 3826c7f..a128efa 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/PathBasedHolderTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/PathBasedHolderTest.java
@@ -18,16 +18,17 @@
*/
package org.apache.sling.auth.core.impl;
+import org.junit.Test;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
public class PathBasedHolderTest {
- @Test public void TestIsPathRequiresHandlerRoot() {
- final PathBasedHolder holder = new PathBasedHolder("/", null){};
+ @Test
+ public void TestIsPathRequiresHandlerRoot() {
+ final PathBasedHolder holder = new PathBasedHolder("/", null) {};
assertTrue(holder.isPathRequiresHandler("/"));
assertTrue(holder.isPathRequiresHandler("/a"));
@@ -38,8 +39,9 @@ public class PathBasedHolderTest {
assertTrue(holder.isPathRequiresHandler("/a/b/c.html"));
}
- @Test public void TestIsPathRequiresHandlerPrefix() {
- final PathBasedHolder holder = new PathBasedHolder("/a/b", null){};
+ @Test
+ public void TestIsPathRequiresHandlerPrefix() {
+ final PathBasedHolder holder = new PathBasedHolder("/a/b", null) {};
assertFalse(holder.isPathRequiresHandler("/"));
assertFalse(holder.isPathRequiresHandler("/a"));
@@ -56,13 +58,13 @@ public class PathBasedHolderTest {
public void test_childNodeAuthenticationHandlerPath() throws Throwable {
final String requestPath = "/content/test/test2";
final String handlerPath = "/content/test";
- final PathBasedHolder holder = new PathBasedHolder(handlerPath, null){};
+ final PathBasedHolder holder = new PathBasedHolder(handlerPath, null) {};
assertTrue(holder.isPathRequiresHandler(requestPath));
}
private void assertPathRequiresHandler(boolean expected, String requestPath, String handlerPath) {
- final PathBasedHolder holder = new PathBasedHolder(handlerPath, null){};
+ final PathBasedHolder holder = new PathBasedHolder(handlerPath, null) {};
assertEquals(expected, holder.isPathRequiresHandler(requestPath));
}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetricsTest.java b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetricsTest.java
index 7c130c9..da8a54a 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetricsTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticationMetricsTest.java
@@ -1,21 +1,26 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl;
+import java.io.Closeable;
+import java.io.IOException;
+
import org.apache.sling.commons.metrics.Meter;
import org.apache.sling.commons.metrics.MetricsService;
import org.apache.sling.commons.metrics.Timer;
@@ -33,9 +38,6 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-import java.io.Closeable;
-import java.io.IOException;
-
public class SlingAuthenticationMetricsTest {
private Meter successMeter = mock(Meter.class);
@@ -87,4 +89,4 @@ public class SlingAuthenticationMetricsTest {
verifyNoMoreInteractions(timer, ctx);
verifyNoInteractions(successMeter, failedMeter);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiJavaxTest.java b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiJavaxTest.java
index 56b6989..acec169 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiJavaxTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiJavaxTest.java
@@ -1,30 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl;
-import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_FAILED_METER_NAME;
-import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_SUCCESS_METER_NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
@@ -37,7 +30,6 @@ import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
@@ -58,6 +50,15 @@ import org.mockito.Mockito;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
+import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_FAILED_METER_NAME;
+import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_SUCCESS_METER_NAME;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
public class SlingAuthenticatorOsgiJavaxTest {
@Rule
@@ -78,7 +79,8 @@ public class SlingAuthenticatorOsgiJavaxTest {
public void before() throws Exception {
ResourceResolver rr = mock(ResourceResolver.class);
- when(resourceResolverFactory.getResourceResolver(any(AuthenticationInfo.class))).thenReturn(rr);
+ when(resourceResolverFactory.getResourceResolver(any(AuthenticationInfo.class)))
+ .thenReturn(rr);
when(timer.time()).thenReturn(ctx);
when(metricsService.meter(AUTHENTICATE_SUCCESS_METER_NAME)).thenReturn(successMeter);
@@ -90,8 +92,11 @@ public class SlingAuthenticatorOsgiJavaxTest {
context.registerInjectActivateService(SlingAuthenticationMetrics.class);
context.registerInjectActivateService(AuthenticationRequirementsManager.class);
- //register a test auth handler
- context.registerService(AuthenticationHandler.class, testAuthHandler, Collections.singletonMap(AuthenticationHandler.PATH_PROPERTY, new String[] {"/"}));
+ // register a test auth handler
+ context.registerService(
+ AuthenticationHandler.class,
+ testAuthHandler,
+ Collections.singletonMap(AuthenticationHandler.PATH_PROPERTY, new String[] {"/"}));
context.registerService(EventHandler.class, testEventHandler);
context.registerService(LoginEventDecorator.class, new TestLoginEventDecorator());
@@ -110,11 +115,11 @@ public class SlingAuthenticatorOsgiJavaxTest {
AuthenticationInfo authInfo = new AuthenticationInfo("testing", "admin", "admin".toCharArray());
authInfo.put(AuthConstants.AUTH_INFO_LOGIN, Boolean.TRUE);
when(req.getRequestURL()).thenReturn(new StringBuffer("/test"));
- when(testAuthHandler.extractCredentials(Mockito.any(), Mockito.any())).thenReturn(authInfo);
+ when(testAuthHandler.extractCredentials(Mockito.any(), Mockito.any()))
+ .thenReturn(authInfo);
},
() -> testEventHandler.collectedEvents(AuthConstants.TOPIC_LOGIN),
- event -> assertEquals("test1Value", event.getProperty("test1"))
- );
+ event -> assertEquals("test1Value", event.getProperty("test1")));
}
/**
@@ -127,18 +132,19 @@ public class SlingAuthenticatorOsgiJavaxTest {
// provide invalid test authInfo
AuthenticationInfo authInfo = new AuthenticationInfo("testing", "invalid", "invalid".toCharArray());
when(req.getRequestURL()).thenReturn(new StringBuffer("/testing"));
- when(testAuthHandler.extractCredentials(Mockito.any(), Mockito.any())).thenReturn(authInfo);
+ when(testAuthHandler.extractCredentials(Mockito.any(), Mockito.any()))
+ .thenReturn(authInfo);
// throw exception to trigger FailedLogin event
try {
- when(resourceResolverFactory.getResourceResolver(authInfo)).thenThrow(new LoginException("Test LoginFailed"));
+ when(resourceResolverFactory.getResourceResolver(authInfo))
+ .thenThrow(new LoginException("Test LoginFailed"));
} catch (LoginException e) {
// should never get here as the LoginException should be caught by the SlingAuthenticator
fail("Unexpected exception caught: " + e.getMessage());
}
},
() -> testEventHandler.collectedEvents(AuthConstants.TOPIC_LOGIN_FAILED),
- event -> assertEquals("test2Value", event.getProperty("test2"))
- );
+ event -> assertEquals("test2Value", event.getProperty("test2")));
}
/**
@@ -149,7 +155,8 @@ public class SlingAuthenticatorOsgiJavaxTest {
* @param collectEvents to do the work of collecting the delivered events
* @param verifyEvent to do the work to assert that the event has the expected state
*/
- protected void assertLoginEvent(BiConsumer<HttpServletRequest, HttpServletResponse> prepareAuthInfo,
+ protected void assertLoginEvent(
+ BiConsumer<HttpServletRequest, HttpServletResponse> prepareAuthInfo,
Supplier<List<Event>> collectEvents,
Consumer<Event> verifyEvent) {
HttpServletRequest req = mock(HttpServletRequest.class);
@@ -169,12 +176,12 @@ public class SlingAuthenticatorOsgiJavaxTest {
// wait for the login event to arrive
Awaitility.await("eventDelivery")
- .atMost(Duration.ofSeconds(5))
- .pollInterval(Duration.ofMillis(100))
- .until(() -> {
- List<Event> events = collectEvents.get();
- return !events.isEmpty();
- });
+ .atMost(Duration.ofSeconds(5))
+ .pollInterval(Duration.ofMillis(100))
+ .until(() -> {
+ List<Event> events = collectEvents.get();
+ return !events.isEmpty();
+ });
List<Event> events = collectEvents.get();
assertEquals(1, events.size());
// make sure the event has the state that we expect
@@ -200,13 +207,11 @@ public class SlingAuthenticatorOsgiJavaxTest {
public void handleEvent(Event event) {
String topic = event.getTopic();
// collect the event if it is one of the topics we are interested in
- if (AuthConstants.TOPIC_LOGIN_FAILED.equals(topic) ||
- AuthConstants.TOPIC_LOGIN.equals(topic)) {
+ if (AuthConstants.TOPIC_LOGIN_FAILED.equals(topic) || AuthConstants.TOPIC_LOGIN.equals(topic)) {
List<Event> list = collectedEvents.computeIfAbsent(topic, t -> new ArrayList<>());
list.add(event);
}
}
-
}
/**
@@ -215,17 +220,19 @@ public class SlingAuthenticatorOsgiJavaxTest {
static class TestLoginEventDecorator implements LoginEventDecorator {
@Override
- public @NotNull void decorateLoginEvent(@NotNull javax.servlet.http.HttpServletRequest request,
- @NotNull AuthenticationInfo authInfo, @NotNull Map<String, Object> eventProperties) {
+ public @NotNull void decorateLoginEvent(
+ @NotNull javax.servlet.http.HttpServletRequest request,
+ @NotNull AuthenticationInfo authInfo,
+ @NotNull Map<String, Object> eventProperties) {
eventProperties.put("test1", "test1Value");
}
@Override
- public @NotNull void decorateLoginFailedEvent(@NotNull javax.servlet.http.HttpServletRequest request,
- @NotNull AuthenticationInfo authInfo, @NotNull Map<String, Object> eventProperties) {
+ public @NotNull void decorateLoginFailedEvent(
+ @NotNull javax.servlet.http.HttpServletRequest request,
+ @NotNull AuthenticationInfo authInfo,
+ @NotNull Map<String, Object> eventProperties) {
eventProperties.put("test2", "test2Value");
}
-
}
-
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiTest.java b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiTest.java
index e931abe..53770a9 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorOsgiTest.java
@@ -1,33 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl;
-import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_FAILED_METER_NAME;
-import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_SUCCESS_METER_NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoInteractions;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
@@ -41,7 +31,6 @@ import java.util.function.Supplier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
@@ -61,6 +50,18 @@ import org.junit.Test;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
+import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_FAILED_METER_NAME;
+import static org.apache.sling.auth.core.impl.SlingAuthenticationMetrics.AUTHENTICATE_SUCCESS_METER_NAME;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
public class SlingAuthenticatorOsgiTest {
@Rule
@@ -81,7 +82,8 @@ public class SlingAuthenticatorOsgiTest {
public void before() throws Exception {
ResourceResolver rr = mock(ResourceResolver.class);
- when(resourceResolverFactory.getResourceResolver(any(AuthenticationInfo.class))).thenReturn(rr);
+ when(resourceResolverFactory.getResourceResolver(any(AuthenticationInfo.class)))
+ .thenReturn(rr);
when(timer.time()).thenReturn(ctx);
when(metricsService.meter(AUTHENTICATE_SUCCESS_METER_NAME)).thenReturn(successMeter);
@@ -93,8 +95,11 @@ public class SlingAuthenticatorOsgiTest {
context.registerInjectActivateService(SlingAuthenticationMetrics.class);
context.registerInjectActivateService(AuthenticationRequirementsManager.class);
- //register a test auth handler
- context.registerService(JakartaAuthenticationHandler.class, testAuthHandler, Collections.singletonMap(JakartaAuthenticationHandler.PATH_PROPERTY, new String[] {"/"}));
+ // register a test auth handler
+ context.registerService(
+ JakartaAuthenticationHandler.class,
+ testAuthHandler,
+ Collections.singletonMap(JakartaAuthenticationHandler.PATH_PROPERTY, new String[] {"/"}));
context.registerService(EventHandler.class, testEventHandler);
context.registerService(JakartaLoginEventDecorator.class, new TestLoginEventDecorator());
@@ -136,8 +141,7 @@ public class SlingAuthenticatorOsgiTest {
when(testAuthHandler.extractCredentials(req, resp)).thenReturn(authInfo);
},
() -> testEventHandler.collectedEvents(AuthConstants.TOPIC_LOGIN),
- event -> assertEquals("test1Value", event.getProperty("test1"))
- );
+ event -> assertEquals("test1Value", event.getProperty("test1")));
}
/**
@@ -153,15 +157,15 @@ public class SlingAuthenticatorOsgiTest {
when(testAuthHandler.extractCredentials(req, resp)).thenReturn(authInfo);
// throw exception to trigger FailedLogin event
try {
- when(resourceResolverFactory.getResourceResolver(authInfo)).thenThrow(new LoginException("Test LoginFailed"));
+ when(resourceResolverFactory.getResourceResolver(authInfo))
+ .thenThrow(new LoginException("Test LoginFailed"));
} catch (LoginException e) {
// should never get here as the LoginException should be caught by the SlingAuthenticator
fail("Unexpected exception caught: " + e.getMessage());
}
},
() -> testEventHandler.collectedEvents(AuthConstants.TOPIC_LOGIN_FAILED),
- event -> assertEquals("test2Value", event.getProperty("test2"))
- );
+ event -> assertEquals("test2Value", event.getProperty("test2")));
}
/**
@@ -172,7 +176,8 @@ public class SlingAuthenticatorOsgiTest {
* @param collectEvents to do the work of collecting the delivered events
* @param verifyEvent to do the work to assert that the event has the expected state
*/
- protected void assertLoginEvent(BiConsumer<HttpServletRequest, HttpServletResponse> prepareAuthInfo,
+ protected void assertLoginEvent(
+ BiConsumer<HttpServletRequest, HttpServletResponse> prepareAuthInfo,
Supplier<List<Event>> collectEvents,
Consumer<Event> verifyEvent) {
HttpServletRequest req = mock(HttpServletRequest.class);
@@ -192,12 +197,12 @@ public class SlingAuthenticatorOsgiTest {
// wait for the login event to arrive
Awaitility.await("eventDelivery")
- .atMost(Duration.ofSeconds(5))
- .pollInterval(Duration.ofMillis(100))
- .until(() -> {
- List<Event> events = collectEvents.get();
- return !events.isEmpty();
- });
+ .atMost(Duration.ofSeconds(5))
+ .pollInterval(Duration.ofMillis(100))
+ .until(() -> {
+ List<Event> events = collectEvents.get();
+ return !events.isEmpty();
+ });
List<Event> events = collectEvents.get();
assertEquals(1, events.size());
// make sure the event has the state that we expect
@@ -223,13 +228,11 @@ public class SlingAuthenticatorOsgiTest {
public void handleEvent(Event event) {
String topic = event.getTopic();
// collect the event if it is one of the topics we are interested in
- if (AuthConstants.TOPIC_LOGIN_FAILED.equals(topic) ||
- AuthConstants.TOPIC_LOGIN.equals(topic)) {
+ if (AuthConstants.TOPIC_LOGIN_FAILED.equals(topic) || AuthConstants.TOPIC_LOGIN.equals(topic)) {
List<Event> list = collectedEvents.computeIfAbsent(topic, t -> new ArrayList<>());
list.add(event);
}
}
-
}
/**
@@ -238,17 +241,19 @@ public class SlingAuthenticatorOsgiTest {
static class TestLoginEventDecorator implements JakartaLoginEventDecorator {
@Override
- public @NotNull void decorateLoginEvent(@NotNull HttpServletRequest request,
- @NotNull AuthenticationInfo authInfo, @NotNull Map<String, Object> eventProperties) {
+ public @NotNull void decorateLoginEvent(
+ @NotNull HttpServletRequest request,
+ @NotNull AuthenticationInfo authInfo,
+ @NotNull Map<String, Object> eventProperties) {
eventProperties.put("test1", "test1Value");
}
@Override
- public @NotNull void decorateLoginFailedEvent(@NotNull HttpServletRequest request,
- @NotNull AuthenticationInfo authInfo, @NotNull Map<String, Object> eventProperties) {
+ public @NotNull void decorateLoginFailedEvent(
+ @NotNull HttpServletRequest request,
+ @NotNull AuthenticationInfo authInfo,
+ @NotNull Map<String, Object> eventProperties) {
eventProperties.put("test2", "test2Value");
}
-
}
-
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorTest.java b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorTest.java
index 220bd16..053a6b9 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorTest.java
@@ -18,11 +18,6 @@
*/
package org.apache.sling.auth.core.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.never;
-
import java.io.IOException;
import java.io.UnsupportedEncodingException;
@@ -31,7 +26,7 @@ import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-
+import junitx.util.PrivateAccessor;
import org.apache.sling.api.SlingJakartaHttpServletRequest;
import org.apache.sling.api.SlingJakartaHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
@@ -47,11 +42,14 @@ import org.mockito.Mockito;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
-import junitx.util.PrivateAccessor;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.never;
public class SlingAuthenticatorTest {
- /**
+ /**
* Helper method to create a default configuration
*/
public static SlingAuthenticator.Config createDefaultConfig() {
@@ -85,20 +83,20 @@ public class SlingAuthenticatorTest {
return context;
}
- private SlingAuthenticator createSlingAuthenticator(final SlingAuthenticator.Config config,
- final String... typeAndPathPairs) {
- final AuthenticationRequirementsManager requirements = new AuthenticationRequirementsManager(createBundleContext(), null, config, callable -> callable.run());
+ private SlingAuthenticator createSlingAuthenticator(
+ final SlingAuthenticator.Config config, final String... typeAndPathPairs) {
+ final AuthenticationRequirementsManager requirements =
+ new AuthenticationRequirementsManager(createBundleContext(), null, config, callable -> callable.run());
final AuthenticationHandlersManager handlers = new AuthenticationHandlersManager(config);
- if ( typeAndPathPairs != null ) {
- int i=0;
- while ( i < typeAndPathPairs.length ) {
- handlers.addHolder(buildAuthHolderForAuthTypeAndPath(typeAndPathPairs[i], typeAndPathPairs[i+1]));
+ if (typeAndPathPairs != null) {
+ int i = 0;
+ while (i < typeAndPathPairs.length) {
+ handlers.addHolder(buildAuthHolderForAuthTypeAndPath(typeAndPathPairs[i], typeAndPathPairs[i + 1]));
i += 2;
}
}
- final SlingAuthenticator slingAuthenticator = new SlingAuthenticator(requirements,
- handlers,
- null, Mockito.mock(BundleContext.class), config);
+ final SlingAuthenticator slingAuthenticator =
+ new SlingAuthenticator(requirements, handlers, null, Mockito.mock(BundleContext.class), config);
return slingAuthenticator;
}
@@ -121,7 +119,6 @@ public class SlingAuthenticatorTest {
checkQuote("string\ttab", "\"string%09tab\"");
checkQuote("test中文", "\"test%E4%B8%AD%E6%96%87\"");
-
try {
SlingAuthenticator.quoteCookieValue("string\rCR");
Assert.fail("Expected IllegalArgumentExcepion on value containing CR");
@@ -148,9 +145,9 @@ public class SlingAuthenticatorTest {
checkUnQuote("\"string\ttab\"", "string\ttab");
}
- //SLING-4864
+ // SLING-4864
@Test
- public void test_isAnonAllowed() throws Throwable {
+ public void test_isAnonAllowed() throws Throwable {
// anon is allowed by default
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
@@ -163,7 +160,7 @@ public class SlingAuthenticatorTest {
}
@Test
- public void test_isAnonNotAllowed() throws Throwable {
+ public void test_isAnonNotAllowed() throws Throwable {
// anon is allowed by default
final SlingAuthenticator.Config config = createDefaultConfig();
Mockito.when(config.auth_annonymous()).thenReturn(false);
@@ -185,8 +182,11 @@ public class SlingAuthenticatorTest {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequest(request, requestChildNode);
- AuthenticationInfo authInfo = (AuthenticationInfo) PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class, HttpServletResponse.class}, new Object[]{request, Mockito.mock(HttpServletResponse.class)});
+ AuthenticationInfo authInfo = (AuthenticationInfo) PrivateAccessor.invoke(
+ slingAuthenticator,
+ "getAuthenticationInfo",
+ new Class[] {HttpServletRequest.class, HttpServletResponse.class},
+ new Object[] {request, Mockito.mock(HttpServletResponse.class)});
/**
* The AUTH TYPE defined above should be used for the path /test and his children: eg /test/childnode.
*/
@@ -242,20 +242,23 @@ public class SlingAuthenticatorTest {
final String PROTECTED_PATH_LONGER = "/resource1.test2";
final String REQUEST_CHILD_NODE = "/resource1.test2";
- final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator(AUTH_TYPE, PROTECTED_PATH, AUTH_TYPE_LONGER, PROTECTED_PATH_LONGER);
+ final SlingAuthenticator slingAuthenticator =
+ this.createSlingAuthenticator(AUTH_TYPE, PROTECTED_PATH, AUTH_TYPE_LONGER, PROTECTED_PATH_LONGER);
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequest(request, REQUEST_CHILD_NODE);
- AuthenticationInfo authInfo = (AuthenticationInfo) PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class, HttpServletResponse.class}, new Object[]{request, Mockito.mock(HttpServletResponse.class)});
+ AuthenticationInfo authInfo = (AuthenticationInfo) PrivateAccessor.invoke(
+ slingAuthenticator,
+ "getAuthenticationInfo",
+ new Class[] {HttpServletRequest.class, HttpServletResponse.class},
+ new Object[] {request, Mockito.mock(HttpServletResponse.class)});
/**
* The AUTH TYPE defined aboved should be used for the path /test and his children: eg /test/childnode.
*/
Assert.assertEquals(AUTH_TYPE_LONGER, authInfo.getAuthType());
}
-
/**
* JIRA: SLING-6053
* Issue can be reproduced with the following steps:
@@ -283,15 +286,19 @@ public class SlingAuthenticatorTest {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequest(request, REQUEST_NOT_PROTECTED_PATH);
- AuthenticationInfo authInfo = (AuthenticationInfo) PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class, HttpServletResponse.class}, new Object[]{request, Mockito.mock(HttpServletResponse.class)});
+ AuthenticationInfo authInfo = (AuthenticationInfo) PrivateAccessor.invoke(
+ slingAuthenticator,
+ "getAuthenticationInfo",
+ new Class[] {HttpServletRequest.class, HttpServletResponse.class},
+ new Object[] {request, Mockito.mock(HttpServletResponse.class)});
/**
* The AUTH TYPE defined aboved should not be used for the path /test2.
*/
Assert.assertNotEquals(AUTH_TYPE, authInfo.getAuthType());
}
- @Test public void testServletRequestListener() {
+ @Test
+ public void testServletRequestListener() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final ServletRequestEvent event = Mockito.mock(ServletRequestEvent.class);
final ServletRequest request = Mockito.mock(ServletRequest.class);
@@ -300,7 +307,8 @@ public class SlingAuthenticatorTest {
slingAuthenticator.requestInitialized(event);
final ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
- Mockito.when(request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER)).thenReturn(resolver);
+ Mockito.when(request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER))
+ .thenReturn(resolver);
slingAuthenticator.requestDestroyed(event);
// verify resolver close, attribute removed
@@ -308,7 +316,8 @@ public class SlingAuthenticatorTest {
Mockito.verify(request).removeAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER);
}
- @Test public void testSetSudoCookieNoSudoBeforeNoSudoAfter() {
+ @Test
+ public void testSetSudoCookieNoSudoBeforeNoSudoAfter() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final AuthenticationInfo info = new AuthenticationInfo("basic");
@@ -319,7 +328,8 @@ public class SlingAuthenticatorTest {
Mockito.verify(res, never()).addCookie(Mockito.any());
}
- @Test public void testSetSudoCookieNoSudoBeforeSudoAfter() {
+ @Test
+ public void testSetSudoCookieNoSudoBeforeSudoAfter() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final AuthenticationInfo info = new AuthenticationInfo("basic");
info.put(ResourceResolverFactory.USER_IMPERSONATION, "newsudo");
@@ -333,7 +343,8 @@ public class SlingAuthenticatorTest {
assertEquals("\"newsudo\"", argument.getValue().getValue());
}
- @Test public void testSetSudoCookieSudoBeforeSameSudoAfter() {
+ @Test
+ public void testSetSudoCookieSudoBeforeSameSudoAfter() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final AuthenticationInfo info = new AuthenticationInfo("basic");
info.put(ResourceResolverFactory.USER_IMPERSONATION, "oldsudo");
@@ -347,7 +358,8 @@ public class SlingAuthenticatorTest {
Mockito.verify(res, never()).addCookie(Mockito.any());
}
- @Test public void testSetSudoCookieSudoBeforeNewSudoAfter() {
+ @Test
+ public void testSetSudoCookieSudoBeforeNewSudoAfter() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final AuthenticationInfo info = new AuthenticationInfo("basic");
info.put(ResourceResolverFactory.USER_IMPERSONATION, "newsudo");
@@ -363,7 +375,8 @@ public class SlingAuthenticatorTest {
assertEquals("\"newsudo\"", argument.getValue().getValue());
}
- @Test public void testSetSudoCookieSudoBeforeNoSudoAfter() {
+ @Test
+ public void testSetSudoCookieSudoBeforeNoSudoAfter() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final AuthenticationInfo info = new AuthenticationInfo("basic");
@@ -378,7 +391,8 @@ public class SlingAuthenticatorTest {
assertEquals("\"\"", argument.getValue().getValue());
}
- @Test public void testSudoCookieFlags() {
+ @Test
+ public void testSudoCookieFlags() {
final SlingAuthenticator slingAuthenticator = this.createSlingAuthenticator();
final AuthenticationInfo info = new AuthenticationInfo("basic");
info.put(ResourceResolverFactory.USER_IMPERSONATION, "newsudo");
@@ -402,7 +416,7 @@ public class SlingAuthenticatorTest {
assertFalse(argument2.getValue().getSecure());
}
- //---------------------------- PRIVATE METHODS -----------------------------
+ // ---------------------------- PRIVATE METHODS -----------------------------
/**
* Mocks the request to accept method calls on path;
@@ -410,8 +424,7 @@ public class SlingAuthenticatorTest {
* @param request http request
* @param requestPath request path
*/
- private void buildExpectationsForRequest(final HttpServletRequest request,
- final String requestPath) {
+ private void buildExpectationsForRequest(final HttpServletRequest request, final String requestPath) {
{
Mockito.when(request.getServletPath()).thenReturn(requestPath);
Mockito.when(request.getServerName()).thenReturn("localhost");
@@ -426,7 +439,8 @@ public class SlingAuthenticatorTest {
* @param authProtectedPath path protected by the auth handler
* @return AbstractAuthenticationHandlerHolder with only an AuthenticationInfo
*/
- private AbstractAuthenticationHandlerHolder buildAuthHolderForAuthTypeAndPath(final String authType, final String authProtectedPath) {
+ private AbstractAuthenticationHandlerHolder buildAuthHolderForAuthTypeAndPath(
+ final String authType, final String authProtectedPath) {
return new AbstractAuthenticationHandlerHolder(authProtectedPath, null) {
@Override
@@ -435,19 +449,20 @@ public class SlingAuthenticatorTest {
}
@Override
- protected AuthenticationInfo doExtractCredentials(HttpServletRequest request, HttpServletResponse response) {
+ protected AuthenticationInfo doExtractCredentials(
+ HttpServletRequest request, HttpServletResponse response) {
return new AuthenticationInfo(authType);
}
@Override
- protected boolean doRequestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ protected boolean doRequestCredentials(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
return false;
}
@Override
- protected void doDropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
-
- }
+ protected void doDropCredentials(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {}
};
}
@@ -469,8 +484,7 @@ public class SlingAuthenticatorTest {
}
@Override
- public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
throw new UnsupportedOperationException("Unimplemented method 'requestCredentials'");
}
@@ -478,6 +492,5 @@ public class SlingAuthenticatorTest {
public void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
throw new UnsupportedOperationException("Unimplemented method 'dropCredentials'");
}
-
}
}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheckTest.java b/src/test/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheckTest.java
index 0327b6b..fce5c29 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheckTest.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/hc/DefaultLoginsHealthCheckTest.java
@@ -1,32 +1,30 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
+ * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
- * regarding copyright ownership. The SF licenses this file
+ * regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations under the License.
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl.hc;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-
import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
+import java.util.Arrays;
+
import org.apache.felix.hc.api.Result;
import org.apache.sling.jcr.api.SlingRepository;
import org.junit.Test;
@@ -35,6 +33,9 @@ import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class DefaultLoginsHealthCheckTest {
private Result getTestResult(String login) throws Exception {
@@ -42,7 +43,7 @@ public class DefaultLoginsHealthCheckTest {
if (login == null) {
SetField.set(c, "logins", Arrays.asList(new String[0]));
} else {
- SetField.set(c, "logins", Arrays.asList(new String[] { login }));
+ SetField.set(c, "logins", Arrays.asList(new String[] {login}));
}
final SlingRepository repo = Mockito.mock(SlingRepository.class);
@@ -51,7 +52,7 @@ public class DefaultLoginsHealthCheckTest {
Mockito.when(repo.login(ArgumentMatchers.any(Credentials.class))).thenAnswer(new Answer<Session>() {
@Override
public Session answer(InvocationOnMock invocation) throws LoginException {
- final SimpleCredentials c = (SimpleCredentials)invocation.getArguments()[0];
+ final SimpleCredentials c = (SimpleCredentials) invocation.getArguments()[0];
if ("admin".equals(c.getUserID())) {
return s;
} else if ("throw".equals(c.getUserID())) {
@@ -60,7 +61,7 @@ public class DefaultLoginsHealthCheckTest {
return null;
}
});
-
+
return c.execute();
}
@@ -78,21 +79,26 @@ public class DefaultLoginsHealthCheckTest {
public void testHealthCheckInvalidLogins() throws Exception {
Result testResult = getTestResult("FOO");
assertFalse("Expecting successful check", testResult.isOk());
- assertTrue("Expected warning in the ResultLog", testResult.toString().contains("WARN Expected login in the form username:password, got [FOO]"));
+ assertTrue(
+ "Expected warning in the ResultLog",
+ testResult.toString().contains("WARN Expected login in the form username:password, got [FOO]"));
}
@Test
public void testHealthCheckEmptyLogins() throws Exception {
Result testResult = getTestResult(null);
assertFalse("Expecting failed check", testResult.isOk());
- assertTrue("Expected warning in the ResultLog", testResult.toString().contains("WARN Did not check any logins, configured logins=[]"));
+ assertTrue(
+ "Expected warning in the ResultLog",
+ testResult.toString().contains("WARN Did not check any logins, configured logins=[]"));
}
@Test
public void testHealthCheckSucceedsWithLoginException() throws Exception {
Result testResult = getTestResult("throw:loginexception");
assertTrue("Expecting successful check", testResult.isOk());
- assertTrue("Expected debug in the ResultLog", testResult.toString().contains("DEBUG Login as [throw] failed, as expected"));
+ assertTrue(
+ "Expected debug in the ResultLog",
+ testResult.toString().contains("DEBUG Login as [throw] failed, as expected"));
}
-
}
diff --git a/src/test/java/org/apache/sling/auth/core/impl/hc/SetField.java b/src/test/java/org/apache/sling/auth/core/impl/hc/SetField.java
index 6df721e..b4e1aba 100644
--- a/src/test/java/org/apache/sling/auth/core/impl/hc/SetField.java
+++ b/src/test/java/org/apache/sling/auth/core/impl/hc/SetField.java
@@ -1,30 +1,30 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
+ * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
- * regarding copyright ownership. The SF licenses this file
+ * regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations under the License.
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.auth.core.impl.hc;
import java.lang.reflect.Field;
public class SetField {
-
+
public static void set(Object o, String name, Object value) throws Exception {
final Field f = o.getClass().getDeclaredField(name);
f.setAccessible(true);
f.set(o, value);
}
-
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/auth/core/spi/AuthenticationInfoTest.java b/src/test/java/org/apache/sling/auth/core/spi/AuthenticationInfoTest.java
index fc4cc1a..792c68e 100644
--- a/src/test/java/org/apache/sling/auth/core/spi/AuthenticationInfoTest.java
+++ b/src/test/java/org/apache/sling/auth/core/spi/AuthenticationInfoTest.java
@@ -18,12 +18,6 @@
*/
package org.apache.sling.auth.core.spi;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-
import javax.jcr.Credentials;
import javax.jcr.SimpleCredentials;
@@ -31,6 +25,12 @@ import org.apache.sling.api.resource.ResourceResolverFactory;
import org.junit.Assert;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
+
public class AuthenticationInfoTest {
// backwards compatible constant tied to jcr/resource
@@ -40,8 +40,7 @@ public class AuthenticationInfoTest {
@Test
public void testClear() {
final char[] pwd = new char[6];
- final AuthenticationInfo info = new AuthenticationInfo("test", "name",
- pwd);
+ final AuthenticationInfo info = new AuthenticationInfo("test", "name", pwd);
Assert.assertEquals("test", info.getAuthType());
Assert.assertEquals("name", info.getUser());
assertSame(pwd, info.getPassword());
@@ -113,8 +112,7 @@ public class AuthenticationInfoTest {
@Test
public void testAuthenticationInfoStringStringCharArray() {
final char[] pwd = new char[6];
- final AuthenticationInfo info = new AuthenticationInfo("test", "name",
- pwd);
+ final AuthenticationInfo info = new AuthenticationInfo("test", "name", pwd);
Assert.assertEquals("test", info.getAuthType());
Assert.assertEquals("name", info.getUser());
assertSame(pwd, info.getPassword());
@@ -123,8 +121,7 @@ public class AuthenticationInfoTest {
@Test
public void testAuthenticationInfoStringStringCharArrayString() {
final char[] pwd = new char[6];
- final AuthenticationInfo info = new AuthenticationInfo("test", "name",
- pwd);
+ final AuthenticationInfo info = new AuthenticationInfo("test", "name", pwd);
Assert.assertEquals("test", info.getAuthType());
Assert.assertEquals("name", info.getUser());
assertSame(pwd, info.getPassword());
@@ -150,8 +147,7 @@ public class AuthenticationInfoTest {
final AuthenticationInfo info = new AuthenticationInfo("test");
Assert.assertEquals("test", info.getAuthType());
Assert.assertEquals("test", info.get(AuthenticationInfo.AUTH_TYPE));
- Assert.assertEquals(info.get(AuthenticationInfo.AUTH_TYPE),
- info.getAuthType());
+ Assert.assertEquals(info.get(AuthenticationInfo.AUTH_TYPE), info.getAuthType());
}
@Test
@@ -196,13 +192,11 @@ public class AuthenticationInfoTest {
@Test
public void testGetPassword() {
final char[] pwd = new char[6];
- final AuthenticationInfo info = new AuthenticationInfo("test", "name",
- pwd);
+ final AuthenticationInfo info = new AuthenticationInfo("test", "name", pwd);
assertSame(pwd, info.getPassword());
assertEquals(String.valueOf(pwd), String.valueOf((char[]) info.get(ResourceResolverFactory.PASSWORD)));
- Assert.assertEquals(info.get(ResourceResolverFactory.PASSWORD),
- info.getPassword());
+ Assert.assertEquals(info.get(ResourceResolverFactory.PASSWORD), info.getPassword());
}
@Test
@@ -228,8 +222,7 @@ public class AuthenticationInfoTest {
final String user = "user";
final char[] pwd = new char[5];
- final AuthenticationInfo infoCred = new AuthenticationInfo("TEST",
- user, pwd);
+ final AuthenticationInfo infoCred = new AuthenticationInfo("TEST", user, pwd);
// credentials not stored in the object
assertFalse(infoCred.containsKey(CREDENTIALS));
@@ -255,10 +248,8 @@ public class AuthenticationInfoTest {
@Test
public void testPutStringObject() {
- final AuthenticationInfo info = new AuthenticationInfo("test", "user",
- new char[2]);
- info.put(CREDENTIALS,
- new SimpleCredentials("user", new char[2]));
+ final AuthenticationInfo info = new AuthenticationInfo("test", "user", new char[2]);
+ info.put(CREDENTIALS, new SimpleCredentials("user", new char[2]));
test_put_fail(info, AuthenticationInfo.AUTH_TYPE, null);
test_put_fail(info, ResourceResolverFactory.USER, null);
@@ -270,20 +261,17 @@ public class AuthenticationInfoTest {
test_put_success(info, AuthenticationInfo.AUTH_TYPE, "new_type");
test_put_success(info, ResourceResolverFactory.USER, "new_user");
- test_put_success(info, ResourceResolverFactory.PASSWORD,
- "new_pwd".toCharArray());
+ test_put_success(info, ResourceResolverFactory.PASSWORD, "new_pwd".toCharArray());
}
- private void test_put_success(final AuthenticationInfo info,
- final String key, final Object value) {
+ private void test_put_success(final AuthenticationInfo info, final String key, final Object value) {
final Object oldValue = info.get(key);
final Object replacedValue = info.put(key, value);
assertSame(oldValue, replacedValue);
assertSame(value, info.get(key));
}
- private void test_put_fail(final AuthenticationInfo info, final String key,
- final Object value) {
+ private void test_put_fail(final AuthenticationInfo info, final String key, final Object value) {
final Object oldValue = info.get(key);
try {
info.put(key, value);
diff --git a/src/test/java/org/apache/sling/auth/core/spi/ReadOnlyAuthenticationInfoTest.java b/src/test/java/org/apache/sling/auth/core/spi/ReadOnlyAuthenticationInfoTest.java
index 1c88ed0..3bb0f11 100644
--- a/src/test/java/org/apache/sling/auth/core/spi/ReadOnlyAuthenticationInfoTest.java
+++ b/src/test/java/org/apache/sling/auth/core/spi/ReadOnlyAuthenticationInfoTest.java
@@ -18,13 +18,6 @@
*/
package org.apache.sling.auth.core.spi;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
-
import java.util.Collection;
import java.util.Collections;
import java.util.Map.Entry;
@@ -33,6 +26,13 @@ import java.util.Set;
import org.junit.Before;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
+
/**
* Verify that ReadOnlyAuthenticationInfo instances are immutable
*/
@@ -42,7 +42,7 @@ public class ReadOnlyAuthenticationInfoTest {
@Before
public void before() {
// create a clone so each test starts with a fresh object
- authInfo = (AuthenticationInfo)AuthenticationInfo.FAIL_AUTH.clone();
+ authInfo = (AuthenticationInfo) AuthenticationInfo.FAIL_AUTH.clone();
}
@Test
@@ -183,5 +183,4 @@ public class ReadOnlyAuthenticationInfoTest {
assertEquals(authInfo, clone);
assertNotSame(authInfo, clone);
}
-
}