This is an automated email from the ASF dual-hosted git repository.
cziegeler pushed a commit to branch master
in repository
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-auth-core.git
The following commit(s) were added to refs/heads/master by this push:
new c9330a0 SLING-9622 : Avoid registration of auth requirements for
aliases and vanity paths (#4)
c9330a0 is described below
commit c9330a0495cb5d61aecb15fb27898afe7902728a
Author: Carsten Ziegeler <[email protected]>
AuthorDate: Wed Aug 5 14:46:43 2020 +0200
SLING-9622 : Avoid registration of auth requirements for aliases and vanity
paths (#4)
* SLING-9622 : Potential solution using a service resource resolver to
resolve the path
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
* SLING-9622 : Handle mapping within auth.core bundle and update auth
requirements when mapping changes
---
pom.xml | 2 +-
.../sling/auth/core/impl/SlingAuthenticator.java | 48 ++-
.../impl/SlingAuthenticatorServiceListener.java | 350 ++++++++++++++++++---
.../sling/engine/auth/AuthenticationHandler.java | 1 +
.../sling/engine/auth/AuthenticationInfo.java | 1 +
.../auth/NoAuthenticationHandlerException.java | 1 +
.../SlingAuthenticatorServiceListenerTest.java | 218 ++++++++++++-
.../auth/core/impl/SlingAuthenticatorTest.java | 107 +++----
8 files changed, 575 insertions(+), 153 deletions(-)
diff --git a/pom.xml b/pom.xml
index d53b354..97d5350 100644
--- a/pom.xml
+++ b/pom.xml
@@ -71,7 +71,7 @@
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.api</artifactId>
- <version>2.18.0</version>
+ <version>2.20.0</version>
<scope>provided</scope>
</dependency>
<dependency>
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 47f1ef9..c2e876a 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
@@ -30,6 +30,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
import javax.jcr.SimpleCredentials;
import javax.security.auth.login.AccountLockedException;
@@ -354,7 +355,7 @@ public class SlingAuthenticator implements Authenticator,
Servlet.class, plugin, props);
serviceListener = SlingAuthenticatorServiceListener.createListener(
- bundleContext, this.authRequiredCache);
+ bundleContext, Executors.newSingleThreadExecutor(),
resourceResolverFactory, this.authRequiredCache);
authHandlerTracker = new AuthenticationHandlerTracker(bundleContext,
authHandlerCache);
@@ -448,7 +449,7 @@ public class SlingAuthenticator implements Authenticator,
}
if (serviceListener != null) {
- bundleContext.removeServiceListener(serviceListener);
+ serviceListener.stop(bundleContext);
serviceListener = null;
}
@@ -478,7 +479,6 @@ public class SlingAuthenticator implements Authenticator,
@Override
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
@@ -741,7 +741,12 @@ public class SlingAuthenticator implements Authenticator,
// ---------- internal
- private String getPath(HttpServletRequest request) {
+ /**
+ * Get the request path from the request
+ * @param request The request
+ * @return The path
+ */
+ private String getPath(final HttpServletRequest request) {
final StringBuilder sb = new StringBuilder();
if (request.getServletPath() != null) {
sb.append(request.getServletPath());
@@ -749,19 +754,21 @@ public class SlingAuthenticator implements Authenticator,
if (request.getPathInfo() != null) {
sb.append(request.getPathInfo());
}
- return sb.toString();
- }
-
- private AuthenticationInfo getAuthenticationInfo(HttpServletRequest
request, HttpServletResponse response) {
-
+ String path = sb.toString();
// Get the path used to select the authenticator, if the SlingServlet
// itself has been requested without any more info, this will be empty
// and we assume the root (SLING-722)
- String path = getPath(request);
if (path.length() == 0) {
path = "/";
}
+ return path;
+ }
+
+ private AuthenticationInfo getAuthenticationInfo(HttpServletRequest
request, HttpServletResponse response) {
+
+ String path = getPath(request);
+
final Collection<AbstractAuthenticationHandlerHolder>[] localArray =
this.authHandlerCache
.findApplicableHolders(request);
for (int m = 0; m < localArray.length; m++) {
@@ -953,9 +960,6 @@ public class SlingAuthenticator implements Authenticator,
private boolean isAnonAllowed(HttpServletRequest request) {
String path = getPath(request);
- if (path.length() == 0) {
- path = "/";
- }
final Collection<AuthenticationRequirementHolder>[] holderSetArray =
authRequiredCache
.findApplicableHolders(request);
@@ -975,10 +979,6 @@ public class SlingAuthenticator implements Authenticator,
}
private boolean isNodeRequiresAuthHandler(String path, String holderPath) {
- if (path == null || holderPath == null) {
- return false;
- }
-
if (("/").equals(holderPath)) {
return true;
}
@@ -993,10 +993,8 @@ public class SlingAuthenticator implements Authenticator,
return true;
}
- if (path.startsWith(holderPath)) {
- if (path.charAt(holderPathLength) == '/' ||
path.charAt(holderPathLength) == '.') {
- return true;
- }
+ if (path.startsWith(holderPath) && (path.charAt(holderPathLength) ==
'/' || path.charAt(holderPathLength) == '.')) {
+ return true;
}
return false;
}
@@ -1502,14 +1500,14 @@ public class SlingAuthenticator implements
Authenticator,
if (ctxPath != null && path.startsWith(ctxPath)) {
path = path.substring(ctxPath.length());
}
+ if (path == null || path.length() == 0) {
+ path = "/";
+ }
+
} else {
path = getPath(request);
}
- if (path == null || path.length() == 0) {
- path = "/";
- }
-
return path;
}
diff --git
a/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListener.java
b/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListener.java
index f1c0c1a..4bf1ab0 100644
---
a/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListener.java
+++
b/src/main/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListener.java
@@ -19,11 +19,22 @@
package org.apache.sling.auth.core.impl;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Dictionary;
import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.sling.api.SlingConstants;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.mapping.ResourceMapper;
import org.apache.sling.auth.core.AuthConstants;
import org.osgi.framework.AllServiceListener;
import org.osgi.framework.BundleContext;
@@ -31,64 +42,251 @@ import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventConstants;
+import org.osgi.service.event.EventHandler;
import org.osgi.util.converter.Converters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-public class SlingAuthenticatorServiceListener implements AllServiceListener {
+/**
+ * Service listener keeping track of all auth requirements registered in
+ * the service registry.
+ *
+ */
+public class SlingAuthenticatorServiceListener implements AllServiceListener,
EventHandler {
+
+ /** Filter expression for auth requirements */
+ 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;
+
+ /** Fake service id to indicate clearing the processing queue */
+ private static final Long CLEAR = -1L;
+ /** Logger */
+ private final Logger logger =
LoggerFactory.getLogger(SlingAuthenticatorServiceListener.class);
+
+ /** Resource resolver factory */
+ private final ResourceResolverFactory resolverFactory;
+
+ /** Auth requirements cache */
private final PathBasedHolderCache<AuthenticationRequirementHolder>
authRequiredCache;
- private final HashMap<Object, Set<String>> regProps = new HashMap<Object,
Set<String>>();
+ /** Cache for registration properties of auth requirements */
+ private final Map<Long, Set<String>> regProps = new ConcurrentHashMap<>();
+
+ /** Cache for registered holders for an auth requirement */
+ private final Map<Long, List<AuthenticationRequirementHolder>> props = new
ConcurrentHashMap<>();
+
+ /** Service registration for the event handler */
+ private ServiceRegistration<EventHandler> serviceRegistration;
+
+ /** Processing queue for changes */
+ private final Map<Long, Action> processingQueue = new LinkedHashMap<>();
- private final HashMap<Object, List<AuthenticationRequirementHolder>> props
= new HashMap<Object, List<AuthenticationRequirementHolder>>();
+ /** Executor for the processing queue */
+ private final Executor executor;
+ /** Flag to indicate whether processing queue is running */
+ private final AtomicBoolean backgroundJobRunning = new
AtomicBoolean(false);
+
+ /**
+ * Create a new listener
+ * @param context Bundle context
+ * @param executor Executor service
+ * @param factory Resource resolver factory
+ * @param authRequiredCache The cache for the auth requirements
+ * @return
+ */
static SlingAuthenticatorServiceListener createListener(
final BundleContext context,
+ final Executor executor,
+ final ResourceResolverFactory factory,
final PathBasedHolderCache<AuthenticationRequirementHolder>
authRequiredCache) {
- SlingAuthenticatorServiceListener listener = new
SlingAuthenticatorServiceListener(authRequiredCache);
+
+ final SlingAuthenticatorServiceListener listener = new
SlingAuthenticatorServiceListener(authRequiredCache,
+ executor,
+ factory);
try {
- final String filter = "(" + AuthConstants.AUTH_REQUIREMENTS +
"=*)";
- context.addServiceListener(listener, filter);
- ServiceReference<?>[] refs = context.getAllServiceReferences(null,
- filter);
+ context.addServiceListener(listener, FILTER_EXPR);
+ final Dictionary<String, Object> props = new Hashtable<>();
+ props.put(EventConstants.EVENT_TOPIC,
SlingConstants.TOPIC_RESOURCE_RESOLVER_MAPPING_CHANGED);
+
listener.setServiceRegistration(context.registerService(EventHandler.class,
listener, props));
+ ServiceReference<?>[] refs = context.getAllServiceReferences(null,
FILTER_EXPR);
if (refs != null) {
- for (ServiceReference<?> ref : refs) {
- listener.addService(ref);
+ for (final ServiceReference<?> ref : refs) {
+ final Long id =
(Long)ref.getProperty(Constants.SERVICE_ID);
+ listener.queue(id, new Action(ActionType.ADDED, ref));
}
}
+
+ listener.schedule();
+
return listener;
} catch (InvalidSyntaxException ise) {
}
return null;
}
- private SlingAuthenticatorServiceListener(final
PathBasedHolderCache<AuthenticationRequirementHolder> authRequiredCache) {
+ /**
+ * Create a new listener
+ * @param authRequiredCache The cache
+ * @param executor For updating
+ * @param factory The resource resolver factory
+ */
+ private SlingAuthenticatorServiceListener(final
PathBasedHolderCache<AuthenticationRequirementHolder> authRequiredCache,
+ final Executor executor,
+ final ResourceResolverFactory factory) {
this.authRequiredCache = authRequiredCache;
+ this.executor = executor;
+ this.resolverFactory = factory;
+ logger.debug("Started auth requirements listener");
+ }
+
+ void setServiceRegistration(final ServiceRegistration<EventHandler> reg) {
+ this.serviceRegistration = reg;
}
+ public void stop(final BundleContext bundleContext) {
+ bundleContext.removeServiceListener(this);
+ if ( this.serviceRegistration != null ) {
+ this.serviceRegistration.unregister();
+ this.serviceRegistration = null;
+ }
+ queue(CLEAR, null);
+ backgroundJobRunning.set(false);
+ logger.debug("Stopped auth requirements listener");
+ }
+
+ private void schedule() {
+ if ( this.backgroundJobRunning.compareAndSet(false, true) ) {
+ this.executor.execute(() -> processQueue());
+ }
+ }
+
+ /**
+ * Handle service registration updates (add, modified, remove)
+ */
@Override
public void serviceChanged(final ServiceEvent event) {
- synchronized ( props ) {
- // 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)
- if ((event.getType() & (ServiceEvent.UNREGISTERING |
ServiceEvent.MODIFIED_ENDMATCH)) != 0) {
- removeService(event.getServiceReference());
+ // 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);
+ if ((event.getType() & (ServiceEvent.UNREGISTERING |
ServiceEvent.MODIFIED_ENDMATCH)) != 0) {
+ queue(id, new Action(ActionType.REMOVED,
event.getServiceReference()));
+ }
+
+ 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) {
+ queue(id, new Action(ActionType.ADDED,
event.getServiceReference()));
+ }
+ schedule();
+ }
+
+ /**
+ * Handle a mapping event
+ */
+ @Override
+ public void handleEvent(final Event event) {
+ queue(UPDATE, null);
+ schedule();
+ }
+
+ /**
+ * Queue a new action
+ * @param id The id of the service
+ * @param action The action to take
+ */
+ private void queue(final long id, final Action action) {
+ logger.debug("Queuing action for service {} : {}", id, action);
+ synchronized ( this.processingQueue ) {
+ if ( id == CLEAR ) {
+ this.processingQueue.clear();
+ } else if ( id == UPDATE ) {
+ for(final Long updateId: this.props.keySet()) {
+ this.processingQueue.putIfAbsent(updateId, new
Action(ActionType.UPDATE, null));
+ }
+ } else {
+ this.processingQueue.remove(id);
+ this.processingQueue.put(id, action);
}
+ }
+ }
- if ((event.getType() & ServiceEvent.MODIFIED ) != 0) {
- modifiedService(event.getServiceReference());
+ /**
+ * Process the queue, one by one
+ * Lazy creation of resource resolver / resource mapper
+ */
+ private void processQueue() {
+ ResourceResolver resolver = null;
+ ResourceMapper mapper = null;
+ try {
+ 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() ) {
+ entry = iter.next();
+ iter.remove();
+ }
+ }
+ 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 ) {
+ try {
+ resolver =
this.resolverFactory.getServiceResourceResolver(null);
+ mapper = resolver.adaptTo(ResourceMapper.class);
+ } catch ( final
org.apache.sling.api.resource.LoginException le) {
+ // ignore
+ }
+ }
+ process(mapper, entry.getKey(), entry.getValue());
+ }
}
- // add requirements for newly registered services and for
- // updated services
- if ((event.getType() & ServiceEvent.REGISTERED ) != 0) {
- addService(event.getServiceReference());
+ } finally {
+ if ( resolver != null ) {
+ resolver.close();
}
}
}
/**
+ * Process a single action
+ * @param mapper
+ * @param id
+ * @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);
+ }
+ }
+ }
+
+ /**
* Register all known services.
*/
void registerAllServices() {
@@ -107,11 +305,30 @@ public class SlingAuthenticatorServiceListener implements
AllServiceListener {
}
}
- private Set<String> buildPathsSet(final String[] authReqPaths) {
+ private Set<String> buildPathsSet(final ResourceMapper mapper, final
String[] authReqPaths) {
final Set<String> paths = new HashSet<>();
- for(final String authReq : authReqPaths) {
- if (authReq != null && authReq.length() > 0) {
- paths.add(authReq);
+ for(String authReq : authReqPaths) {
+ if (authReq != null ) {
+ authReq = authReq.trim();
+ if ( authReq.length() > 0 ) {
+ final String prefix;
+ if ( authReq.startsWith("+") ) {
+ prefix = null;
+ authReq = authReq.substring(1);
+ } else if ( authReq.startsWith("-") ) {
+ prefix = "-";
+ authReq = authReq.substring(1);
+ } else {
+ prefix = null;
+ }
+ paths.add(prefix == null ? authReq :
prefix.concat(authReq));
+
+ if ( mapper != null ) {
+ for(final String mappedPath :
mapper.getAllMappings(authReq)) {
+ paths.add(prefix == null ? mappedPath :
prefix.concat(mappedPath));
+ }
+ }
+ }
}
}
return paths;
@@ -121,22 +338,23 @@ public class SlingAuthenticatorServiceListener implements
AllServiceListener {
* Process a new service with auth requirements
* @param ref The service reference
*/
- private void addService(final ServiceReference<?> ref) {
+ 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 != null ) {
- final Set<String> paths = buildPathsSet(authReqPaths);
+ if ( authReqPaths.length > 0 ) {
+ final Long id = (Long)ref.getProperty(Constants.SERVICE_ID);
+ final Set<String> paths = buildPathsSet(mapper, authReqPaths);
if ( !paths.isEmpty() ) {
final List<AuthenticationRequirementHolder> authReqList = new
ArrayList<AuthenticationRequirementHolder>();
- for (final String authReq : paths) {
- authReqList.add(AuthenticationRequirementHolder.fromConfig(
- authReq, ref));
+ for(final String authReq : paths) {
+
authReqList.add(AuthenticationRequirementHolder.fromConfig(authReq, ref));
}
- // keep original set for modified
- regProps.put(ref.getProperty(Constants.SERVICE_ID), paths);
+ // keep original
+ regProps.put(id, paths);
registerService(authReqList);
- props.put(ref.getProperty(Constants.SERVICE_ID), authReqList);
+ props.put(id, authReqList);
+ logger.debug("Added auth requirements for service {} : {}",
id, paths);
}
}
}
@@ -145,18 +363,19 @@ public class SlingAuthenticatorServiceListener implements
AllServiceListener {
* Process a modified service with auth requirements
* @param ref The service reference
*/
- private void modifiedService(final ServiceReference<?> ref) {
+ private void modifiedService(final ResourceMapper mapper, final
ServiceReference<?> ref) {
final String[] authReqPaths =
Converters.standardConverter().convert(ref.getProperty(AuthConstants.AUTH_REQUIREMENTS)).to(String[].class);
- if ( authReqPaths != null ) {
- final Set<String> oldPaths =
regProps.get(ref.getProperty(Constants.SERVICE_ID));
+ final Long id = (Long)ref.getProperty(Constants.SERVICE_ID);
+ if ( authReqPaths.length > 0 ) {
+ final Set<String> oldPaths = regProps.get(id);
if ( oldPaths == null ) {
- addService(ref);
+ addService(mapper, ref);
} else {
- final Set<String> paths = buildPathsSet(authReqPaths);
+ final Set<String> paths = buildPathsSet(mapper, authReqPaths);
if ( paths.isEmpty() ) {
- removeService(ref);
+ removeService(id);
} else {
- final List<AuthenticationRequirementHolder> authReqs =
props.get(ref.getProperty(Constants.SERVICE_ID));
+ final List<AuthenticationRequirementHolder> authReqs =
props.get(id);
// compare sets
for(final String oldPath : oldPaths) {
if ( !paths.contains(oldPath) ) {
@@ -174,11 +393,12 @@ public class SlingAuthenticatorServiceListener implements
AllServiceListener {
authRequiredCache.addHolder(holder);
}
}
- regProps.put(ref.getProperty(Constants.SERVICE_ID), paths);
+ regProps.put(id, paths);
+ logger.debug("Updated auth requirements for service {} :
{}", id, paths);
}
}
} else {
- removeService(ref);
+ removeService(id);
}
}
@@ -186,13 +406,43 @@ public class SlingAuthenticatorServiceListener implements
AllServiceListener {
* Process a removed service with auth requirements
* @param ref The service reference
*/
- private void removeService(final ServiceReference<?> ref) {
- final List<AuthenticationRequirementHolder> authReqs =
props.remove(ref.getProperty(Constants.SERVICE_ID));
+ private void removeService(final Long id) {
+ final List<AuthenticationRequirementHolder> authReqs =
props.remove(id);
if (authReqs != null) {
for (final AuthenticationRequirementHolder authReq : authReqs) {
authRequiredCache.removeHolder(authReq);
}
}
- regProps.remove(ref.getProperty(Constants.SERVICE_ID));
+ regProps.remove(id);
+ logger.debug("Removed auth requirements for service {}", id);
+ }
+
+ /**
+ * Action type for the queued execution
+ *
+ */
+ public enum ActionType {
+ ADDED, MODIFIED, REMOVED, UPDATE
+ }
+
+ /**
+ * Action for the queued execution
+ *
+ */
+ public static final class Action {
+
+ public final ActionType type;
+
+ public final ServiceReference<?> reference;
+
+ public Action(final ActionType type, final ServiceReference<?> ref) {
+ this.type = type;
+ this.reference = ref;
+ }
+
+ @Override
+ public String toString() {
+ return "Action [type=" + type + ", reference=" + reference + "]";
+ }
}
}
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 f8d068c..394e107 100644
--- a/src/main/java/org/apache/sling/engine/auth/AuthenticationHandler.java
+++ b/src/main/java/org/apache/sling/engine/auth/AuthenticationHandler.java
@@ -32,6 +32,7 @@ import javax.servlet.http.HttpServletResponse;
* {@link org.apache.sling.auth.core.spi.AuthenticationHandler}
* instead
*/
+@Deprecated
public interface AuthenticationHandler {
/**
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 8d51d31..71e77fc 100644
--- a/src/main/java/org/apache/sling/engine/auth/AuthenticationInfo.java
+++ b/src/main/java/org/apache/sling/engine/auth/AuthenticationInfo.java
@@ -27,6 +27,7 @@ import javax.jcr.Credentials;
*
* @deprecated see {@link AuthenticationHandler}
*/
+@Deprecated
public class AuthenticationInfo {
/**
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 a5a5c60..a85c273 100644
---
a/src/main/java/org/apache/sling/engine/auth/NoAuthenticationHandlerException.java
+++
b/src/main/java/org/apache/sling/engine/auth/NoAuthenticationHandlerException.java
@@ -34,6 +34,7 @@ import org.apache.sling.api.SlingException;
*
* @deprecated see {@link Authenticator}
*/
+@Deprecated
@SuppressWarnings("serial")
public class NoAuthenticationHandlerException extends SlingException {
diff --git
a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListenerTest.java
b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListenerTest.java
index c8d36dc..c87a1bc 100644
---
a/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListenerTest.java
+++
b/src/test/java/org/apache/sling/auth/core/impl/SlingAuthenticatorServiceListenerTest.java
@@ -25,8 +25,13 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.mapping.ResourceMapper;
import org.apache.sling.auth.core.AuthConstants;
import org.junit.Test;
import org.osgi.framework.BundleContext;
@@ -39,7 +44,18 @@ public class SlingAuthenticatorServiceListenerTest {
private void assertPaths(final
PathBasedHolderCache<AuthenticationRequirementHolder> cache,
final String[] paths,
final ServiceReference<?>[] refs) {
- assertEquals(paths.length, refs.length);
+ assertPaths(cache, paths, refs, null);
+ }
+
+ 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 ) {
+ assertEquals("Wrong input to assert paths", paths.length,
requireAuth.length);
+ }
+
assertEquals(paths.length, cache.getHolders().size());
for(final AuthenticationRequirementHolder h : cache.getHolders()) {
boolean found = false;
@@ -47,6 +63,10 @@ public class SlingAuthenticatorServiceListenerTest {
while ( !found && index < paths.length ) {
if (paths[index].equals(h.path) &&
refs[index].equals(h.serviceReference) ) {
found = true;
+
+ if ( requireAuth != null ) {
+ assertEquals(requireAuth[index],
h.requiresAuthentication());
+ }
} else {
index++;
}
@@ -75,30 +95,78 @@ public class SlingAuthenticatorServiceListenerTest {
return ref;
}
- @Test public void testAddRemoveRegistration() {
+ private ResourceResolverFactory createFactoryForMapper(final
ResourceMapper mapper) throws LoginException {
+ final ResourceResolverFactory factory =
mock(ResourceResolverFactory.class);
+
+ final ResourceResolver resolver = mock(ResourceResolver.class);
+
+ when(factory.getServiceResourceResolver(null)).thenReturn(resolver);
+
+ when(resolver.adaptTo(ResourceMapper.class)).thenReturn(mapper);
+
+ return factory;
+ }
+
+ @Test public void testAddRemoveRegistration() throws LoginException {
final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
final BundleContext context = mock(BundleContext.class);
- final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, cache);
+ final ResourceMapper mapper = mock(ResourceMapper.class);
+
when(mapper.getAllMappings("/path1")).thenReturn(Collections.singleton("/path1"));
+ final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
assertTrue(cache.getHolders().isEmpty());
final ServiceReference<?> ref = createServiceReference(new String[]
{"/path1"});
listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
- assertEquals(1, cache.getHolders().size());
assertPaths(cache, new String[] {"/path1"},
new ServiceReference<?>[] {ref});
- assertEquals(ref, cache.getHolders().get(0).serviceReference);
listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING,
ref));
assertTrue(cache.getHolders().isEmpty());
}
- @Test public void testDuplicateRegistration() {
+ @Test public void testAddUpdateRemoveRegistration() throws LoginException {
final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
final BundleContext context = mock(BundleContext.class);
- final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, cache);
+ 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 SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
+
+ // add
+ final ServiceReference<?> ref = createServiceReference(new String[]
{"/path1", "/path2"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
+
+ assertPaths(cache, 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"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref));
+
+ assertPaths(cache, new String[] {"/path2", "/path2a", "/path3",
"/path3a"},
+ new ServiceReference<?>[] {ref, ref, ref, ref},
+ new boolean[] {true, true, true, true});
+
+ // remmove
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING,
ref));
+
+ assertTrue(cache.getHolders().isEmpty());
+ }
+
+ @Test public void testDuplicateRegistration() throws LoginException {
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
+ final BundleContext context = mock(BundleContext.class);
+ 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 SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
final ServiceReference<?> ref1 = createServiceReference(new String[]
{"/path1", "/path1", "/path2"});
listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref1));
@@ -117,10 +185,16 @@ public class SlingAuthenticatorServiceListenerTest {
assertTrue(cache.getHolders().isEmpty());
}
- @Test public void testAddRemoveRegistrations() {
+ @Test public void testAddRemoveRegistrations() throws LoginException {
final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
final BundleContext context = mock(BundleContext.class);
- final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, cache);
+ 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"));
+
when(mapper.getAllMappings("/path4")).thenReturn(Collections.singleton("/path4"));
+
when(mapper.getAllMappings("/path5")).thenReturn(Collections.singleton("/path5"));
+ final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
final ServiceReference<?> ref1 = createServiceReference(new String[]
{"/path1"});
listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref1));
@@ -147,10 +221,16 @@ public class SlingAuthenticatorServiceListenerTest {
assertTrue(cache.getHolders().isEmpty());
}
- @Test public void testModifyRegistration() {
+ @Test public void testModifyRegistration() throws LoginException {
final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
final BundleContext context = mock(BundleContext.class);
- final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, cache);
+ 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"));
+
when(mapper.getAllMappings("/path4")).thenReturn(Collections.singleton("/path4"));
+
when(mapper.getAllMappings("/path5")).thenReturn(Collections.singleton("/path5"));
+ final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
final ServiceReference<?> ref1 = createServiceReference(new String[]
{"/path1", "/path2", "/path3"});
listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref1));
@@ -169,4 +249,120 @@ public class SlingAuthenticatorServiceListenerTest {
assertTrue(cache.getHolders().isEmpty());
}
+
+ @Test public void testRegistrationWithMapping() throws LoginException {
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
+ final BundleContext context = mock(BundleContext.class);
+ final ResourceMapper mapper = mock(ResourceMapper.class);
+
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1",
"/path2", "/path3"));
+ final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
+
+ final ServiceReference<?> ref = createServiceReference(new String[]
{"/path1"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
+
+ assertPaths(cache, new String[] {"/path1", "/path2", "/path3"},
+ new ServiceReference<?>[] {ref, ref, ref});
+
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING,
ref));
+
+ assertTrue(cache.getHolders().isEmpty());
+ }
+
+ @Test public void testRegistrationAndUpdatingMapping() throws
LoginException {
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
+ final BundleContext context = mock(BundleContext.class);
+ final ResourceMapper mapper = mock(ResourceMapper.class);
+
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1",
"/path2", "/path3"));
+ final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
+
+ final ServiceReference<?> ref = createServiceReference(new String[]
{"/path1"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
+
+ assertPaths(cache, new String[] {"/path1", "/path2", "/path3"},
+ new ServiceReference<?>[] {ref, ref, ref});
+
+ // update mapper
+
when(mapper.getAllMappings("/path1")).thenReturn(Arrays.asList("/path1",
"/path5"));
+ listener.handleEvent(null);
+
+ assertPaths(cache, new String[] {"/path1", "/path5"},
+ new ServiceReference<?>[] {ref, ref});
+
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING,
ref));
+
+ assertTrue(cache.getHolders().isEmpty());
+ }
+
+ @Test public void testAllowDeny() throws LoginException {
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
+ final BundleContext context = mock(BundleContext.class);
+
+ final SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(null), cache);
+
+ final ServiceReference<?> ref = createServiceReference(new String[]
{"-/path1", "+/path2", "/path3"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
+
+ assertPaths(cache, new String[] {"/path1", "/path2", "/path3"},
+ new ServiceReference<?>[] {ref, ref, ref},
+ new boolean[] {false, true, true});
+ }
+
+ @Test public void testAllowDenyWithMapping() throws LoginException {
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
+ final BundleContext context = mock(BundleContext.class);
+
+ 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 SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
+
+ final ServiceReference<?> ref = createServiceReference(new String[]
{"-/path1", "+/path2", "/path3"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
+
+ assertPaths(cache, 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"));
+
when(mapper.getAllMappings("/path2")).thenReturn(Arrays.asList("/path2",
"/path2c"));
+
when(mapper.getAllMappings("/path3")).thenReturn(Arrays.asList("/path3",
"/path3c"));
+ listener.handleEvent(null);
+
+ assertPaths(cache, 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 {
+ final PathBasedHolderCache<AuthenticationRequirementHolder> cache =
new PathBasedHolderCache<AuthenticationRequirementHolder>();
+ final BundleContext context = mock(BundleContext.class);
+ 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 SlingAuthenticatorServiceListener listener =
SlingAuthenticatorServiceListener.createListener(context, callable ->
callable.run(), createFactoryForMapper(mapper), cache);
+
+ // add
+ final ServiceReference<?> ref = createServiceReference(new String[]
{"+/path1", "-/path2"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
ref));
+
+ assertPaths(cache, 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"});
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref));
+
+ assertPaths(cache, new String[] {"/path1", "/path1a", "/path2",
"/path2a"},
+ new ServiceReference<?>[] {ref, ref, ref, ref},
+ new boolean[] {false, false, true, true});
+
+ // remmove
+ listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING,
ref));
+
+ assertTrue(cache.getHolders().isEmpty());
+ }
}
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 7b2e16a..d6b5c3c 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
@@ -20,21 +20,20 @@ package org.apache.sling.auth.core.impl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Assert;
import org.junit.Test;
+import org.mockito.Mockito;
+
import junitx.util.PrivateAccessor;
public class SlingAuthenticatorTest {
- private final Mockery context = new JUnit4Mockery();
-
@Test
public void test_quoteCookieValue() throws UnsupportedEncodingException {
@@ -90,21 +89,10 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(new AuthenticationRequirementHolder("/",
false, null));
PrivateAccessor.setField(slingAuthenticator, "authRequiredCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
- context.checking(new Expectations() {
- {
- allowing(request).getServletPath();
- will(returnValue(null));
- allowing(request).getPathInfo();
- will(returnValue(null));
- allowing(request).getServerName();
- will(returnValue("localhost"));
- allowing(request).getServerPort();
- will(returnValue(80));
- allowing(request).getScheme();
- will(returnValue("http"));
- }
- });
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
+ Mockito.when(request.getServerName()).thenReturn("localhost");
+ Mockito.when(request.getServerPort()).thenReturn(80);
+ Mockito.when(request.getScheme()).thenReturn("http");
Boolean allowed = (Boolean)
PrivateAccessor.invoke(slingAuthenticator,"isAnonAllowed", new
Class[]{HttpServletRequest.class},new Object[]{request});
Assert.assertTrue(allowed);
@@ -127,17 +115,17 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_CHILD_NODE, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.assertTrue(AUTH_TYPE.equals(authInfo.getAuthType()));
}
-
+
/**
* Test is OK for same node;
* @throws Throwable
@@ -154,17 +142,17 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_CHILD_NODE, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.assertTrue(AUTH_TYPE.equals(authInfo.getAuthType()));
}
-
+
/**
* Test is OK for same node with ending slash;
* @throws Throwable
@@ -181,17 +169,17 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_CHILD_NODE, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.assertTrue(AUTH_TYPE.equals(authInfo.getAuthType()));
}
-
+
/**
* Test is OK for same node with extension
* @throws Throwable
@@ -208,11 +196,11 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_CHILD_NODE, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.
*/
@@ -231,17 +219,17 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_CHILD_NODE, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.assertTrue(AUTH_TYPE.equals(authInfo.getAuthType()));
}
-
+
@Test
public void test_childNodeShouldHaveAuthenticationInfoLonger() throws
Throwable {
final String AUTH_TYPE = "AUTH_TYPE_TEST";
@@ -255,19 +243,19 @@ public class SlingAuthenticatorTest {
PathBasedHolderCache<AbstractAuthenticationHandlerHolder>
authRequiredCache = new
PathBasedHolderCache<AbstractAuthenticationHandlerHolder>();
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE_LONGER,
PROTECTED_PATH_LONGER));
-
+
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_CHILD_NODE, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.assertTrue(AUTH_TYPE_LONGER.equals(authInfo.getAuthType()));
}
-
+
/**
* JIRA: SLING-6053
@@ -297,32 +285,32 @@ public class SlingAuthenticatorTest {
authRequiredCache.addHolder(buildAuthHolderForAuthTypeAndPath(AUTH_TYPE,
PROTECTED_PATH));
PrivateAccessor.setField(slingAuthenticator, "authHandlerCache",
authRequiredCache);
- final HttpServletRequest request =
context.mock(HttpServletRequest.class);
+ final HttpServletRequest request =
Mockito.mock(HttpServletRequest.class);
buildExpectationsForRequestPathAndAuthPath(request,
REQUEST_NOT_PROTECTED_PATH, PROTECTED_PATH);
AuthenticationInfo authInfo = (AuthenticationInfo)
PrivateAccessor.invoke(slingAuthenticator, "getAuthenticationInfo",
- new Class[]{HttpServletRequest.class,
HttpServletResponse.class}, new Object[]{request,
context.mock(HttpServletResponse.class)});
+ 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.assertFalse(AUTH_TYPE.equals(authInfo.getAuthType()));
}
-
+
@Test
public void test_childNodeAuthenticationHandlerPath() throws Throwable {
final String requestPath = "/content/test/test2";
final String handlerPath = "/content/test";
SlingAuthenticator slingAuthenticator = new SlingAuthenticator();
-
+
Assert.assertTrue( (boolean)PrivateAccessor.invoke(slingAuthenticator,
"isNodeRequiresAuthHandler", new Class[] {String.class, String.class}, new
Object[] {requestPath, handlerPath}));
}
-
+
@Test
public void test_siblingNodeAuthenticationHandlerPath() throws Throwable {
final String requestPath =
"/content/test2.html/en/2016/09/19/test.html";
final String handlerPath = "/content/test";
SlingAuthenticator slingAuthenticator = new SlingAuthenticator();
-
+
Assert.assertFalse(
(boolean)PrivateAccessor.invoke(slingAuthenticator,
"isNodeRequiresAuthHandler", new Class[] {String.class, String.class}, new
Object[] {requestPath, handlerPath}));
}
@@ -331,7 +319,7 @@ public class SlingAuthenticatorTest {
final String requestPath = "/content/test";
final String handlerPath = "/content/test";
SlingAuthenticator slingAuthenticator = new SlingAuthenticator();
-
+
Assert.assertTrue( (boolean)PrivateAccessor.invoke(slingAuthenticator,
"isNodeRequiresAuthHandler", new Class[] {String.class, String.class}, new
Object[] {requestPath, handlerPath}));
}
@@ -340,7 +328,7 @@ public class SlingAuthenticatorTest {
final String requestPath = "/content/test";
final String handlerPath = "/";
SlingAuthenticator slingAuthenticator = new SlingAuthenticator();
-
+
Assert.assertTrue( (boolean)PrivateAccessor.invoke(slingAuthenticator,
"isNodeRequiresAuthHandler", new Class[] {String.class, String.class}, new
Object[] {requestPath, handlerPath}));
}
@@ -349,7 +337,7 @@ public class SlingAuthenticatorTest {
final String requestPath =
"/content/test.selector1.selector2.html/en/2016/test.html";
final String handlerPath = "/content/test";
SlingAuthenticator slingAuthenticator = new SlingAuthenticator();
-
+
Assert.assertTrue( (boolean)PrivateAccessor.invoke(slingAuthenticator,
"isNodeRequiresAuthHandler", new Class[] {String.class, String.class}, new
Object[] {requestPath, handlerPath}));
}
@@ -358,7 +346,7 @@ public class SlingAuthenticatorTest {
final String requestPath =
"/content/test.selector1.selector2.html/en/2016/09/19/test.html";
final String handlerPath = "/content/test2";
SlingAuthenticator slingAuthenticator = new SlingAuthenticator();
-
+
Assert.assertFalse(
(boolean)PrivateAccessor.invoke(slingAuthenticator,
"isNodeRequiresAuthHandler", new Class[] {String.class, String.class}, new
Object[] {requestPath, handlerPath}));
}
@@ -393,24 +381,11 @@ public class SlingAuthenticatorTest {
final String requestPath,
final String authProtectedPath) {
{
- context.checking(new Expectations() {
- {
- allowing(request).getServletPath();
- will(returnValue(requestPath));
- allowing(request).getPathInfo();
- will(returnValue(null));
- allowing(request).getServerName();
- will(returnValue("localhost"));
- allowing(request).getServerPort();
- will(returnValue(80));
- allowing(request).getScheme();
- will(returnValue("http"));
- allowing(request).getAttribute("path");
- will(returnValue(requestPath));
- allowing(request).setAttribute("path", requestPath);
- allowing(request).setAttribute("path", authProtectedPath);
- }
- });
+ Mockito.when(request.getServletPath()).thenReturn(requestPath);
+ Mockito.when(request.getServerName()).thenReturn("localhost");
+ Mockito.when(request.getServerPort()).thenReturn(80);
+ Mockito.when(request.getScheme()).thenReturn("http");
+ Mockito.when(request.getAttribute("path")).thenReturn(requestPath);
}
}