Remove ContextHolder and introduce SecurityContext.

This commit is contained in:
Ben Alex 2005-05-07 09:11:37 +00:00
parent 52064d5db4
commit 6a9abe5d90
74 changed files with 995 additions and 2208 deletions

View File

@ -16,9 +16,7 @@
package net.sf.acegisecurity.adapters.jboss;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -73,12 +71,10 @@ public class JbossIntegrationFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
Object principal = extractFromContainer(request);
if ((principal != null) && principal instanceof Authentication) {
sc.setAuthentication((Authentication) principal);
SecurityContext.setAuthentication((Authentication) principal);
if (logger.isDebugEnabled()) {
logger.debug(

View File

@ -20,9 +20,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.adapters.PrincipalAcegiUserToken;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import org.springframework.mock.web.MockHttpServletRequest;
@ -81,9 +79,8 @@ public class JbossIntegrationFilterTests extends TestCase {
filter.doFilter(request, null, chain);
assertEquals(principal,
SecureContextUtils.getSecureContext().getAuthentication());
ContextHolder.setContext(null);
assertEquals(principal, SecurityContext.getAuthentication());
SecurityContext.setAuthentication(null);
}
public void testReturnsNullIfContextReturnsSomethingOtherThanASubject()
@ -95,7 +92,7 @@ public class JbossIntegrationFilterTests extends TestCase {
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testReturnsNullIfInitialContextHasNullPrincipal()
@ -107,7 +104,7 @@ public class JbossIntegrationFilterTests extends TestCase {
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testReturnsNullIfInitialContextHasNullSubject()
@ -119,7 +116,7 @@ public class JbossIntegrationFilterTests extends TestCase {
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testReturnsNullIfInitialContextIsNull()
@ -130,7 +127,7 @@ public class JbossIntegrationFilterTests extends TestCase {
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testReturnsNullIfPrincipalNotAnAuthenticationImplementation()
@ -146,7 +143,7 @@ public class JbossIntegrationFilterTests extends TestCase {
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testTestingObjectReturnsInitialContext()
@ -157,12 +154,12 @@ public class JbossIntegrationFilterTests extends TestCase {
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,

View File

@ -16,8 +16,7 @@
package net.sf.acegisecurity.adapters;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -36,7 +35,7 @@ import javax.servlet.http.HttpServletRequest;
/**
* Populates <code>ContextHolder</code> with the <code>Authentication</code>
* Populates <code>SecurityContext</code> with the <code>Authentication</code>
* obtained from the container's
* <code>HttpServletRequest.getUserPrincipal()</code>.
*
@ -46,11 +45,12 @@ import javax.servlet.http.HttpServletRequest;
*
* <p>
* This filter <b>never</b> preserves the <code>Authentication</code> on the
* <code>ContextHolder</code> - it is replaced every request.
* <code>SecurityContext</code> - it is replaced every request.
* </p>
*
* <p>
* See {@link net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter} for further information.
* See {@link net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter}
* for further information.
* </p>
*
* @author Ben Alex
@ -70,18 +70,16 @@ public class HttpRequestIntegrationFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
if (request instanceof HttpServletRequest) {
Principal principal = ((HttpServletRequest) request)
.getUserPrincipal();
if ((principal != null) && principal instanceof Authentication) {
sc.setAuthentication((Authentication) principal);
SecurityContext.setAuthentication((Authentication) principal);
if (logger.isDebugEnabled()) {
logger.debug(
"ContextHolder updated with Authentication from container: '"
"SecurityContext updated with Authentication from container: '"
+ principal + "'");
}
} else {

View File

@ -1,46 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
import java.io.Serializable;
/**
* Holds objects that are needed on every request.
*
* <P>
* A <code>Context</code> will be sent between application tiers via a {@link
* ContextHolder}.
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public interface Context extends Serializable {
//~ Methods ================================================================
/**
* Check the <code>Context</code> is properly configured.
*
* <P>
* This allows implementations to confirm they are valid, as this method is
* automatically called by the {@link ContextInterceptor}.
* </p>
*
* @throws ContextInvalidException if the <code>Context</code> is invalid.
*/
public void validate() throws ContextInvalidException;
}

View File

@ -1,55 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
import org.springframework.core.NestedRuntimeException;
/**
* Abstract superclass for all exceptions thrown in the context package and
* subpackages.
*
* <p>
* Note that this is a runtime (unchecked) exception.
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public abstract class ContextException extends NestedRuntimeException {
//~ Constructors ===========================================================
/**
* Constructs a <code>ContextException</code> with the specified message
* and root cause.
*
* @param msg the detail message
* @param t the root cause
*/
public ContextException(String msg, Throwable t) {
super(msg, t);
}
/**
* Constructs a <code>ContextException</code> with the specified message
* and no root cause.
*
* @param msg the detail message
*/
public ContextException(String msg) {
super(msg);
}
}

View File

@ -1,48 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
/**
* Thrown if a {@link ContextHolder} object does not contain a valid {@link
* Context}.
*
* @author Ben Alex
* @version $Id$
*/
public class ContextHolderEmptyException extends ContextException {
//~ Constructors ===========================================================
/**
* Constructs a <code>ContextHolderEmptyException</code> with the specified
* message.
*
* @param msg the detail message
*/
public ContextHolderEmptyException(String msg) {
super(msg);
}
/**
* Constructs a <code>ContextHolderEmptyException</code> with the specified
* message and root cause.
*
* @param msg the detail message
* @param t root cause
*/
public ContextHolderEmptyException(String msg, Throwable t) {
super(msg, t);
}
}

View File

@ -1,30 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
/**
* Basic concrete implementation of a {@link Context}.
*
* @author Ben Alex
* @version $Id$
*/
public class ContextImpl implements Context {
//~ Methods ================================================================
public void validate() throws ContextInvalidException {
// Nothing to validate.
}
}

View File

@ -1,58 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Ensures the {@link ContextHolder} contains a valid {@link Context}.
*
* <p>
* This interceptor works by calling {@link Context#validate()} before
* proceeding with method invocations. It is configured in the bean context
* with a <code>ProxyFactoryBean</code>.
* </p>
*
* @author Ben Alex
* @version $Id$
*
* @see Context#validate()
*/
public class ContextInterceptor implements MethodInterceptor {
//~ Static fields/initializers =============================================
private static final Log logger = LogFactory.getLog(ContextInterceptor.class);
//~ Methods ================================================================
public Object invoke(MethodInvocation mi) throws Throwable {
if (ContextHolder.getContext() == null) {
throw new ContextHolderEmptyException("ContextHolder does not contain a Context",
null);
}
ContextHolder.getContext().validate();
Object ret = mi.proceed();
return ret;
}
}

View File

@ -1,50 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
/**
* Thrown if a {@link Context} is not valid, according to {@link
* Context#validate()}.
*
* @author Ben Alex
* @version $Id$
*
* @see Context#validate()
*/
public class ContextInvalidException extends ContextException {
//~ Constructors ===========================================================
/**
* Constructs a <code>ContextInvalidException</code> with the specified
* message.
*
* @param msg the detail message.
*/
public ContextInvalidException(String msg) {
super(msg);
}
/**
* Constructs a <code>ContextInvalidException</code> with the specified
* message and root cause.
*
* @param msg the detail message.
* @param t root cause
*/
public ContextInvalidException(String msg, Throwable t) {
super(msg, t);
}
}

View File

@ -15,11 +15,11 @@
package net.sf.acegisecurity.context;
import net.sf.acegisecurity.Authentication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import java.io.IOException;
import javax.servlet.Filter;
@ -34,23 +34,17 @@ import javax.servlet.http.HttpSession;
/**
* <p>
* Populates the <code>ContextHolder</code> with information obtained from the
* <code>HttpSession</code>.
* Populates the <code>SecurityContext</code> with information obtained from
* the <code>HttpSession</code>.
* </p>
*
* <p>
* The <code>HttpSession</code> will be queried to retrieve the
* <code>Context</code> that should be stored against the
* <code>ContextHolder</code> for the duration of the web request. At the end
* of the web request, any updates made to the <code>ContextHolder</code> will
* be persisted back to the <code>HttpSession</code> by this filter.
* </p>
*
* <p>
* If a valid <code>Context</code> cannot be obtained from the
* <code>HttpSession</code> for whatever reason, a fresh <code>Context</code>
* will be created and used instead. The created object will be of the
* instance defined by the {@link #setContext(Class)} method.
* <code>Authentication</code> that should be stored against the
* <code>SecurityContext</code> for the duration of the web request. At the
* end of the web request, any updates made to the
* <code>SecurityContext</code> will be persisted back to the
* <code>HttpSession</code> by this filter.
* </p>
*
* <p>
@ -58,11 +52,9 @@ import javax.servlet.http.HttpSession;
* already exist. If at the end of the web request the
* <code>HttpSession</code> does not exist, a <code>HttpSession</code> will
* <b>only</b> be created if the current contents of
* <code>ContextHolder</code> are not {@link
* java.lang.Object#equals(java.lang.Object)} to a <code>new</code> instance
* of {@link #setContext(Class)}. This avoids needless
* <code>HttpSession</code> creation, but automates the storage of changes
* made to the <code>ContextHolder</code>.
* <code>SecurityContext</code> are not <code>null</code>. This avoids
* needless <code>HttpSession</code> creation, but automates the storage of
* changes made to the <code>SecurityContext</code>.
* </p>
*
* <P>
@ -76,35 +68,30 @@ import javax.servlet.http.HttpSession;
* similar clients that will never present the same <code>jsessionid</code>
* etc), the {@link #setAllowSessionCreation(boolean)} should be set to
* <code>false</code>. Only do this if you really need to conserve server
* memory and ensure all classes using the <code>ContextHolder</code> are
* designed to have no persistence of the <code>Context</code> between web
* requests.
* memory and ensure all classes using the <code>SecurityContext</code> are
* designed to have no persistence of the <code>Authentication</code> between
* web requests.
* </p>
*
* <p>
* This filter MUST be executed BEFORE any authentication procesing mechanisms.
* Authentication processing mechanisms (eg BASIC, CAS processing filters etc)
* expect the <code>ContextHolder</code> to contain a valid
* <code>SecureContext</code> by the time they execute.
* This filter MUST appear BEFORE any other Acegi Security related filters,
* because this filter WILL REMOVE any <code>Authentication</code> it finds in
* the <code>SecurityContext</code>.
* </p>
*
* @author Ben Alex
* @author Patrick Burleson
* @version $Id$
*/
public class HttpSessionContextIntegrationFilter implements InitializingBean,
Filter {
public class HttpSessionContextIntegrationFilter implements Filter {
//~ Static fields/initializers =============================================
protected static final Log logger = LogFactory.getLog(HttpSessionContextIntegrationFilter.class);
private static final String FILTER_APPLIED = "__acegi_session_integration_filter_applied";
public static final String ACEGI_SECURITY_CONTEXT_KEY = "ACEGI_SECURITY_CONTEXT";
public static final String ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY = "ACEGI_SECURITY_AUTHENTICATION_CONTEXT";
//~ Instance fields ========================================================
private Class context;
private Object contextObject;
/**
* Indicates if this filter can create a <code>HttpSession</code> if needed
* (sessions are always created sparingly, but setting this value to false
@ -122,24 +109,6 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean,
return allowSessionCreation;
}
public void setContext(Class secureContext) {
this.context = secureContext;
}
public Class getContext() {
return context;
}
public void afterPropertiesSet() throws Exception {
if ((this.context == null)
|| (!Context.class.isAssignableFrom(this.context))) {
throw new IllegalArgumentException(
"context must be defined and implement Context (typically use net.sf.acegisecurity.context.security.SecureContextImpl)");
}
this.contextObject = generateNewContext();
}
/**
* Does nothing. We use IoC container lifecycle services instead.
*/
@ -155,14 +124,16 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean,
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
}
if (ContextHolder.getContext() != null) {
// Nullify the ThreadLocal if it currently contains data (it shouldn't)
if (SecurityContext.getAuthentication() != null) {
if (logger.isWarnEnabled()) {
logger.warn(
"ContextHolder should have been null but contained: '"
+ ContextHolder.getContext() + "'; setting to null now");
"SecurityContext should have been null but contained: '"
+ SecurityContext.getAuthentication()
+ "'; setting to null now");
}
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
HttpSession httpSession = null;
@ -175,29 +146,30 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean,
if (httpSession != null) {
httpSessionExistedAtStartOfRequest = true;
Object contextObject = httpSession.getAttribute(ACEGI_SECURITY_CONTEXT_KEY);
Object authenticationObject = httpSession.getAttribute(ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY);
if (contextObject != null) {
if (contextObject instanceof Context) {
if (authenticationObject != null) {
// HttpSession provided an Authentication object
if (authenticationObject instanceof Authentication) {
if (logger.isDebugEnabled()) {
logger.debug(
"Obtained from ACEGI_SECURITY_CONTEXT a valid Context and set to ContextHolder: '"
+ contextObject + "'");
"Obtained from ACEGI_SECURITY_AUTHENTICATION_CONTEXT a valid Authentication and set to SecurityContext: '"
+ authenticationObject + "'");
}
ContextHolder.setContext((Context) contextObject);
SecurityContext.setAuthentication((Authentication) authenticationObject);
} else {
if (logger.isWarnEnabled()) {
logger.warn(
"ACEGI_SECURITY_CONTEXT did not contain a Context but contained: '"
+ contextObject
+ "'; are you improperly modifying the HttpSession directly (you should always use ContextHolder) or using the HttpSession attribute reserved for this class?");
"ACEGI_SECURITY_AUTHENTICATION_CONTEXT did not contain an Authentication but contained: '"
+ authenticationObject
+ "'; are you improperly modifying the HttpSession directly (you should always use SecurityContext) or using the HttpSession attribute reserved for this class?");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"HttpSession returned null object for ACEGI_SECURITY_CONTEXT");
"HttpSession returned null object for ACEGI_SECURITY_AUTHENTICATION_CONTEXT");
}
}
} else {
@ -206,25 +178,15 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean,
}
}
if (ContextHolder.getContext() == null) {
ContextHolder.setContext(generateNewContext());
if (logger.isDebugEnabled()) {
logger.debug(
"As ContextHolder null, setup ContextHolder with a fresh new instance: '"
+ ContextHolder.getContext() + "'");
}
}
// Make the HttpSession null, as we want to ensure we don't keep
// a reference to the HttpSession laying around in case the
// chain.doFilter() invalidates it.
// Make the HttpSession null, as we want to ensure we don't keep any
// reference to the HttpSession laying around in memory (in case the
// chain.doFilter() we're about to invoke decides to invalidate it).
httpSession = null;
// Proceed with chain
chain.doFilter(request, response);
// Store context back to HttpSession
// Store Authentication back to HttpSession
try {
httpSession = ((HttpServletRequest) request).getSession(false);
} catch (IllegalStateException ignored) {}
@ -232,21 +194,21 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean,
if ((httpSession == null) && httpSessionExistedAtStartOfRequest) {
if (logger.isDebugEnabled()) {
logger.debug(
"HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session");
"HttpSession is now null, but was not null at start of request; session was invalidated during filter chain, so we will NOT create a new session now");
}
}
// Generate a HttpSession only if we need to
// Generate a HttpSession *only* if we have to
if ((httpSession == null) && !httpSessionExistedAtStartOfRequest) {
if (!allowSessionCreation) {
if (logger.isDebugEnabled()) {
logger.debug(
"Whilst ContextHolder contents have changed, the HttpSessionContextIntegrationFilter is prohibited from creating a HttpSession by the allowSessionCreation property being false");
"The HttpSessionContextIntegrationFilter is prohibited from creating a HttpSession by the allowSessionCreation property being false");
}
} else if (!contextObject.equals(ContextHolder.getContext())) {
} else if (SecurityContext.getAuthentication() != null) {
if (logger.isDebugEnabled()) {
logger.debug(
"HttpSession being created as ContextHolder contents are non-default");
"HttpSession being created as SecurityContext contents are non-null");
}
try {
@ -255,44 +217,32 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean,
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"HttpSession still null, but ContextHolder has not changed from default: ' "
+ ContextHolder.getContext()
+ "'; not creating HttpSession or storing ContextHolder contents");
"SecurityContext contents and HttpSession are both null; not creating HttpSession");
}
}
}
// If HttpSession exists, store current ContextHolder contents
// If HttpSession exists or was just created, store current SecurityContext contents
if (httpSession != null) {
httpSession.setAttribute(ACEGI_SECURITY_CONTEXT_KEY,
ContextHolder.getContext());
httpSession.setAttribute(ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY,
SecurityContext.getAuthentication());
if (logger.isDebugEnabled()) {
logger.debug("Context stored to HttpSession: '"
+ ContextHolder.getContext() + "'");
logger.debug("SecurityContext stored to HttpSession: '"
+ SecurityContext.getAuthentication() + "'");
}
}
// Remove ContextHolder contents
ContextHolder.setContext(null);
// Remove SecurityContext contents, ready for next request
SecurityContext.setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug(
"ContextHolder set to null as request processing completed");
"SecurityContext set to null as request processing completed");
}
}
}
public Context generateNewContext() throws ServletException {
try {
return (Context) this.context.newInstance();
} catch (InstantiationException ie) {
throw new ServletException(ie);
} catch (IllegalAccessException iae) {
throw new ServletException(iae);
}
}
/**
* Does nothing. We use IoC container lifecycle services instead.
*

View File

@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -15,24 +15,30 @@
package net.sf.acegisecurity.context;
import net.sf.acegisecurity.Authentication;
/**
* Associates a given {@link Context} with the current execution thread.
* Associates a given {@link Authentication} with the current execution thread,
* along with new threads the current execution thread may spawn.
*
* @author Ben Alex
* @version $Id$
*
* @see java.lang.InheritableThreadLocal
*/
public class ContextHolder {
public class SecurityContext {
//~ Static fields/initializers =============================================
private static ThreadLocal contextHolder = new ThreadLocal();
private static InheritableThreadLocal authenticationHolder = new InheritableThreadLocal();
//~ Methods ================================================================
public static void setContext(Context context) {
contextHolder.set(context);
public static void setAuthentication(Authentication authentication) {
authenticationHolder.set(authentication);
}
public static Context getContext() {
return (Context) contextHolder.get();
public static Authentication getAuthentication() {
return (Authentication) authenticationHolder.get();
}
}

View File

@ -17,8 +17,7 @@ package net.sf.acegisecurity.context.httpinvoker;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationCredentialsNotFoundException;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
@ -87,38 +86,25 @@ public class AuthenticationSimpleHttpInvokerRequestExecutor
throws IOException, AuthenticationCredentialsNotFoundException {
super.prepareConnection(con, contentLength);
if ((ContextHolder.getContext() != null)
&& (ContextHolder.getContext() instanceof SecureContext)) {
Authentication auth = ((SecureContext) ContextHolder.getContext())
.getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
if ((auth != null) && (auth.getPrincipal() != null)
&& (auth.getCredentials() != null)) {
String base64 = auth.getPrincipal().toString() + ":"
+ auth.getCredentials().toString();
con.setRequestProperty("Authorization",
"Basic "
+ new String(Base64.encodeBase64(base64.getBytes())));
if ((auth != null) && (auth.getPrincipal() != null)
&& (auth.getCredentials() != null)) {
String base64 = auth.getPrincipal().toString() + ":"
+ auth.getCredentials().toString();
con.setRequestProperty("Authorization",
"Basic " + new String(Base64.encodeBase64(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger.debug(
"HttpInvocation now presenting via BASIC authentication ContextHolder-derived: "
+ auth.toString());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"Unable to set BASIC authentication header as ContextHolder: "
+ ContextHolder.getContext()
+ "; did not provide valid Authentication: " + auth);
}
if (logger.isDebugEnabled()) {
logger.debug(
"HttpInvocation now presenting via BASIC authentication ContextHolder-derived: "
+ auth.toString());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"Unable to set BASIC authentication header as ContextHolder: "
+ ContextHolder.getContext()
+ "; does not provide a SecureContext");
"Unable to set BASIC authentication header as SecurityContext did not provide valid Authentication: "
+ auth);
}
}

View File

@ -4,7 +4,11 @@ Provides a "request context".
<p>
A request context is associated with the current execution thread. It holds
objects that would otherwise need to be included in many method signatures,
such as for authentication.
such as for authentication.</p>
<p><b>The majority of this package has been deprecated. Please use the
<code>SecurityContext</code> and <code>HttpSessionContextIntegrationFilter</code>
classes only.</b></p>
</body>
</html>

View File

@ -15,8 +15,8 @@
package net.sf.acegisecurity.context.rmi;
import net.sf.acegisecurity.context.Context;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.SecurityContext;
import org.aopalliance.intercept.MethodInvocation;
@ -30,18 +30,20 @@ import java.lang.reflect.InvocationTargetException;
/**
* The actual <code>RemoteInvocation</code> that is passed from the client to
* the server, which contains the contents of {@link ContextHolder}.
* the server, which contains the contents of {@link SecurityContext}, being
* an {@link Authentication} object.
*
* <p>
* When constructed on the client via {@link
* net.sf.acegisecurity.context.rmi.ContextPropagatingRemoteInvocationFactory},
* the contents of the <code>ContextHolder</code> are stored inside the
* the contents of the <code>SecurityContext</code> are stored inside the
* object. The object is then passed to the server that is processing the
* remote invocation. Upon the server invoking the remote invocation, it will
* retrieve the passed contents of the <code>ContextHolder</code> and set them
* to the server-side <code>ContextHolder</code> whilst the target object is
* invoked. When the target invocation has been completed, the server-side
* <code>ContextHolder</code> will be reset to <code>null</code>.
* retrieve the passed contents of the <code>SecurityContext</code> and set
* them to the server-side <code>SecurityContext</code> whilst the target
* object is invoked. When the target invocation has been completed, the
* server-side <code>SecurityContext</code> will be reset to
* <code>null</code>.
* </p>
*
* @author James Monaghan
@ -55,7 +57,7 @@ public class ContextPropagatingRemoteInvocation extends RemoteInvocation {
//~ Instance fields ========================================================
private Context context;
private Authentication authentication;
//~ Constructors ===========================================================
@ -67,10 +69,11 @@ public class ContextPropagatingRemoteInvocation extends RemoteInvocation {
*/
public ContextPropagatingRemoteInvocation(MethodInvocation methodInvocation) {
super(methodInvocation);
context = ContextHolder.getContext();
authentication = SecurityContext.getAuthentication();
if (logger.isDebugEnabled()) {
logger.debug("RemoteInvocation now has context of: " + context);
logger.debug("RemoteInvocation now has authentication: "
+ authentication);
}
}
@ -91,18 +94,18 @@ public class ContextPropagatingRemoteInvocation extends RemoteInvocation {
public Object invoke(Object targetObject)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
ContextHolder.setContext(context);
SecurityContext.setAuthentication(authentication);
if (logger.isDebugEnabled()) {
logger.debug("Set ContextHolder to contain: " + context);
logger.debug("Set SecurityContext to contain: " + authentication);
}
Object result = super.invoke(targetObject);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug("Set ContextHolder to null");
logger.debug("Set SecurityContext to null");
}
return result;

View File

@ -1,40 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context.security;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.Context;
/**
* A {@link Context} that also stores {@link Authentication} information.
*
* <p>
* This interface must be implemented on contexts that will be presented to the
* Acegi Security System for Spring, as it is required by the {@link
* net.sf.acegisecurity.intercept.AbstractSecurityInterceptor}.
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public interface SecureContext extends Context {
//~ Methods ================================================================
public void setAuthentication(Authentication newAuthentication);
public Authentication getAuthentication();
}

View File

@ -1,83 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context.security;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.ContextImpl;
import net.sf.acegisecurity.context.ContextInvalidException;
/**
* Basic concrete implementation of a {@link SecureContext}.
*
* @author Ben Alex
* @version $Id$
*/
public class SecureContextImpl extends ContextImpl implements SecureContext {
//~ Instance fields ========================================================
private Authentication authentication;
//~ Methods ================================================================
public void setAuthentication(Authentication newAuthentication) {
this.authentication = newAuthentication;
}
public Authentication getAuthentication() {
return this.authentication;
}
public boolean equals(Object obj) {
if (obj instanceof SecureContextImpl) {
SecureContextImpl test = (SecureContextImpl) obj;
if ((this.getAuthentication() == null)
&& (test.getAuthentication() == null)) {
return true;
}
if ((this.getAuthentication() != null)
&& (test.getAuthentication() != null)
&& this.getAuthentication().equals(test.getAuthentication())) {
return true;
}
}
return false;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
if (this.authentication == null) {
sb.append(": Null authentication");
} else {
sb.append(": Authentication: " + this.authentication);
}
return sb.toString();
}
public void validate() throws ContextInvalidException {
super.validate();
if (authentication == null) {
throw new ContextInvalidException("Authentication not set");
}
}
}

View File

@ -1,45 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context.security;
import net.sf.acegisecurity.context.ContextHolder;
/**
* A simple static method for quickly accessing the <code>SecureContext</code>.
*
* <p>
* Expects the <code>ContextHolder</code> to be populated and contain a valid
* <code>SecureContext</code>.
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public class SecureContextUtils {
//~ Methods ================================================================
public static SecureContext getSecureContext() {
if ((ContextHolder.getContext() == null)
|| !(ContextHolder.getContext() instanceof SecureContext)) {
throw new IllegalStateException("ContextHolder invalid: '"
+ ContextHolder.getContext()
+ "': are your filters ordered correctly? HttpSessionContextIntegrationFilter should have already executed by this time (look for it in the stack dump below)");
}
return (SecureContext) ContextHolder.getContext();
}
}

View File

@ -1,7 +0,0 @@
<html>
<body>
Provides a <code>Context</code> that is designed to be compatible with
Acegi Security.
</body>
</html>

View File

@ -25,9 +25,7 @@ import net.sf.acegisecurity.AuthenticationManager;
import net.sf.acegisecurity.ConfigAttribute;
import net.sf.acegisecurity.ConfigAttributeDefinition;
import net.sf.acegisecurity.RunAsManager;
import net.sf.acegisecurity.context.Context;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.intercept.event.AuthenticationCredentialsNotFoundEvent;
import net.sf.acegisecurity.intercept.event.AuthenticationFailureEvent;
import net.sf.acegisecurity.intercept.event.AuthorizationFailureEvent;
@ -43,6 +41,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import java.util.HashSet;
@ -222,61 +221,70 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(getSecureObjectClass(), "Subclass must provide a non-null response to getSecureObjectClass()");
Assert.notNull(getSecureObjectClass(),
"Subclass must provide a non-null response to getSecureObjectClass()");
Assert.notNull(this.authenticationManager, "An AuthenticationManager is required");
Assert.notNull(this.authenticationManager,
"An AuthenticationManager is required");
Assert.notNull(this.accessDecisionManager, "An AccessDecisionManager is required");
Assert.notNull(this.accessDecisionManager,
"An AccessDecisionManager is required");
Assert.notNull(this.runAsManager, "A RunAsManager is required");
Assert.notNull(this.obtainObjectDefinitionSource(), "An ObjectDefinitionSource is required");
Assert.notNull(this.obtainObjectDefinitionSource(),
"An ObjectDefinitionSource is required");
if (!this.obtainObjectDefinitionSource().supports(getSecureObjectClass())) {
throw new IllegalArgumentException("ObjectDefinitionSource does not support secure object class: "
+ getSecureObjectClass());
throw new IllegalArgumentException(
"ObjectDefinitionSource does not support secure object class: "
+ getSecureObjectClass());
}
if (!this.runAsManager.supports(getSecureObjectClass())) {
throw new IllegalArgumentException("RunAsManager does not support secure object class: "
+ getSecureObjectClass());
throw new IllegalArgumentException(
"RunAsManager does not support secure object class: "
+ getSecureObjectClass());
}
if (!this.accessDecisionManager.supports(getSecureObjectClass())) {
throw new IllegalArgumentException("AccessDecisionManager does not support secure object class: "
+ getSecureObjectClass());
throw new IllegalArgumentException(
"AccessDecisionManager does not support secure object class: "
+ getSecureObjectClass());
}
if ((this.afterInvocationManager != null)
&& !this.afterInvocationManager.supports(getSecureObjectClass())) {
throw new IllegalArgumentException("AfterInvocationManager does not support secure object class: "
+ getSecureObjectClass());
&& !this.afterInvocationManager.supports(getSecureObjectClass())) {
throw new IllegalArgumentException(
"AfterInvocationManager does not support secure object class: "
+ getSecureObjectClass());
}
if (this.validateConfigAttributes) {
Iterator iter = this.obtainObjectDefinitionSource()
.getConfigAttributeDefinitions();
.getConfigAttributeDefinitions();
if (iter == null) {
if (logger.isWarnEnabled()) {
logger.warn("Could not validate configuration attributes as the MethodDefinitionSource did not return a ConfigAttributeDefinition Iterator");
logger.warn(
"Could not validate configuration attributes as the MethodDefinitionSource did not return a ConfigAttributeDefinition Iterator");
}
} else {
Set set = new HashSet();
while (iter.hasNext()) {
ConfigAttributeDefinition def = (ConfigAttributeDefinition) iter
.next();
.next();
Iterator attributes = def.getConfigAttributes();
while (attributes.hasNext()) {
ConfigAttribute attr = (ConfigAttribute) attributes
.next();
.next();
if (!this.runAsManager.supports(attr)
&& !this.accessDecisionManager.supports(attr)
&& ((this.afterInvocationManager == null)
|| !this.afterInvocationManager.supports(attr))) {
&& !this.accessDecisionManager.supports(attr)
&& ((this.afterInvocationManager == null)
|| !this.afterInvocationManager.supports(attr))) {
set.add(attr);
}
}
@ -287,8 +295,9 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
logger.info("Validated configuration attributes");
}
} else {
throw new IllegalArgumentException("Unsupported configuration attributes: "
+ set.toString());
throw new IllegalArgumentException(
"Unsupported configuration attributes: "
+ set.toString());
}
}
}
@ -319,10 +328,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
+ token.getAuthentication().toString());
}
SecureContext secureContext = (SecureContext) ContextHolder
.getContext();
secureContext.setAuthentication(token.getAuthentication());
ContextHolder.setContext(secureContext);
SecurityContext.setAuthentication(token.getAuthentication());
}
if (afterInvocationManager != null) {
@ -336,44 +342,36 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
protected InterceptorStatusToken beforeInvocation(Object object) {
Assert.notNull(object, "Object was null");
Assert.isTrue(getSecureObjectClass().isAssignableFrom(object.getClass()), "Security invocation attempted for object " + object
+ " but AbstractSecurityInterceptor only configured to support secure objects of type: "
+ getSecureObjectClass());
Assert.isTrue(getSecureObjectClass().isAssignableFrom(object.getClass()),
"Security invocation attempted for object " + object
+ " but AbstractSecurityInterceptor only configured to support secure objects of type: "
+ getSecureObjectClass());
ConfigAttributeDefinition attr = this.obtainObjectDefinitionSource()
.getAttributes(object);
.getAttributes(object);
if (attr != null) {
if (logger.isDebugEnabled()) {
logger.debug("Secure object: " + object.toString()
+ "; ConfigAttributes: " + attr.toString());
+ "; ConfigAttributes: " + attr.toString());
}
// Ensure ContextHolder presents a populated SecureContext
if ((ContextHolder.getContext() == null)
|| !(ContextHolder.getContext() instanceof SecureContext)) {
credentialsNotFound("A valid SecureContext was not provided in the RequestContext",
object, attr);
}
SecureContext context = (SecureContext) ContextHolder.getContext();
// We check for just the property we're interested in (we do
// not call Context.validate() like the ContextInterceptor)
if (context.getAuthentication() == null) {
credentialsNotFound("Authentication credentials were not found in the SecureContext",
object, attr);
if (SecurityContext.getAuthentication() == null) {
credentialsNotFound("Authentication credentials were not found in the SecurityContext",
object, attr);
}
// Attempt authentication
Authentication authenticated;
try {
authenticated = this.authenticationManager.authenticate(context
authenticated = this.authenticationManager.authenticate(SecurityContext
.getAuthentication());
} catch (AuthenticationException authenticationException) {
AuthenticationFailureEvent event = new AuthenticationFailureEvent(object,
attr, context.getAuthentication(),
attr, SecurityContext.getAuthentication(),
authenticationException);
this.context.publishEvent(event);
@ -386,8 +384,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
logger.debug("Authenticated: " + authenticated.toString());
}
context.setAuthentication(authenticated);
ContextHolder.setContext((Context) context);
SecurityContext.setAuthentication(authenticated);
// Attempt authorization
try {
@ -414,22 +411,22 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
if (runAs == null) {
if (logger.isDebugEnabled()) {
logger.debug("RunAsManager did not change Authentication object");
logger.debug(
"RunAsManager did not change Authentication object");
}
return new InterceptorStatusToken(authenticated, false, attr,
object); // no further work post-invocation
object); // no further work post-invocation
} else {
if (logger.isDebugEnabled()) {
logger.debug("Switching to RunAs Authentication: "
+ runAs.toString());
+ runAs.toString());
}
context.setAuthentication(runAs);
ContextHolder.setContext((Context) context);
SecurityContext.setAuthentication(runAs);
return new InterceptorStatusToken(authenticated, true, attr,
object); // revert to token.Authenticated post-invocation
object); // revert to token.Authenticated post-invocation
}
} else {
if (logger.isDebugEnabled()) {
@ -439,21 +436,16 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean,
this.context.publishEvent(new PublicInvocationEvent(object));
// Set Authentication object (if it exists) to be unauthenticated
if ((ContextHolder.getContext() != null)
&& ContextHolder.getContext() instanceof SecureContext) {
SecureContext context = (SecureContext) ContextHolder
.getContext();
if (context.getAuthentication() != null) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication object detected and tagged as unauthenticated");
}
Authentication authenticated = context.getAuthentication();
authenticated.setAuthenticated(false);
context.setAuthentication(authenticated);
ContextHolder.setContext((Context) context);
if (SecurityContext.getAuthentication() != null) {
if (logger.isDebugEnabled()) {
logger.debug(
"Authentication object detected and tagged as unauthenticated");
}
Authentication authenticated = SecurityContext
.getAuthentication();
authenticated.setAuthenticated(false);
SecurityContext.setAuthentication(authenticated);
}
return null; // no further work post-invocation

View File

@ -15,8 +15,12 @@
package net.sf.acegisecurity.intercept.web;
import net.sf.acegisecurity.*;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.AccessDeniedException;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.AuthenticationTrustResolver;
import net.sf.acegisecurity.AuthenticationTrustResolverImpl;
import net.sf.acegisecurity.InsufficientAuthenticationException;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.ui.AbstractProcessingFilter;
import net.sf.acegisecurity.util.PortResolver;
import net.sf.acegisecurity.util.PortResolverImpl;
@ -30,7 +34,12 @@ import org.springframework.util.Assert;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -184,7 +193,7 @@ public class SecurityEnforcementFilter implements Filter, InitializingBean {
sendStartAuthentication(fi, authentication);
} catch (AccessDeniedException accessDenied) {
if (authenticationTrustResolver.isAnonymous(
SecureContextUtils.getSecureContext().getAuthentication())) {
SecurityContext.getAuthentication())) {
if (logger.isDebugEnabled()) {
logger.debug("Access is denied (user is anonymous); redirecting to authentication entry point",
accessDenied);

View File

@ -16,11 +16,8 @@
package net.sf.acegisecurity.providers.anonymous;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.intercept.web.AuthenticationEntryPoint;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.dao.memory.UserAttribute;
import net.sf.acegisecurity.ui.basicauth.BasicProcessingFilterEntryPoint;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -133,22 +130,20 @@ public class AnonymousProcessingFilter implements Filter, InitializingBean {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
if (applyAnonymousForThisRequest(request)) {
if (sc.getAuthentication() == null) {
sc.setAuthentication(createAuthentication(request));
if (SecurityContext.getAuthentication() == null) {
SecurityContext.setAuthentication(createAuthentication(request));
if (logger.isDebugEnabled()) {
logger.debug(
"Replaced ContextHolder with anonymous token: '"
+ sc.getAuthentication() + "'");
+ SecurityContext.getAuthentication() + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"ContextHolder not replaced with anonymous token, as ContextHolder already contained: '"
+ sc.getAuthentication() + "'");
+ SecurityContext.getAuthentication() + "'");
}
}
}

View File

@ -16,8 +16,7 @@
package net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -38,8 +37,8 @@ import javax.security.auth.spi.LoginModule;
* conjunction. <br>
* The {@link JaasAuthenticationProvider} allows Acegi to authenticate against
* Jaas. <br>
* The SecureContextLoginModule allows a Jaas based application to authenticate
* against Acegi.
* The SecureContextLoginModule allows a Jaas based application to
* authenticate against Acegi.
*
* @author Brian Moseley
* @author Ray Krueger
@ -123,19 +122,7 @@ public class SecureContextLoginModule implements LoginModule {
* @throws LoginException if the authentication fails
*/
public boolean login() throws LoginException {
if (ContextHolder.getContext() == null) {
log.debug("no security context found");
return false;
}
if (!(ContextHolder.getContext() instanceof SecureContext)) {
log.debug("security context not instance of SecureContext");
return false;
}
SecureContext context = (SecureContext) ContextHolder.getContext();
authen = context.getAuthentication();
authen = SecurityContext.getAuthentication();
if (authen == null) {
throw new LoginException("Authentication not found in security"

View File

@ -19,8 +19,7 @@ import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.acl.AclEntry;
import net.sf.acegisecurity.acl.AclManager;
import net.sf.acegisecurity.acl.basic.AbstractBasicAclEntry;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -134,19 +133,16 @@ public class AclTag extends TagSupport {
return Tag.EVAL_BODY_INCLUDE;
}
if ((ContextHolder.getContext() == null)
|| !(ContextHolder.getContext() instanceof SecureContext)
|| (((SecureContext) ContextHolder.getContext()).getAuthentication() == null)) {
if (SecurityContext.getAuthentication() == null) {
if (logger.isDebugEnabled()) {
logger.debug(
"ContextHolder did not return a non-null Authentication object, so skipping tag body");
"SecurityContext did not return a non-null Authentication object, so skipping tag body");
}
return Tag.SKIP_BODY;
}
Authentication auth = ((SecureContext) ContextHolder.getContext())
.getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
ApplicationContext context = getContext(pageContext);
Map beans = context.getBeansOfType(AclManager.class, false, false);

View File

@ -17,8 +17,7 @@ package net.sf.acegisecurity.taglibs.authz;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import java.io.IOException;
@ -32,11 +31,10 @@ import javax.servlet.jsp.tagext.TagSupport;
* convenient access to the current <code>Authentication</code> object.
*
* <p>
* Whilst JSPs can access the <code>ContextHolder</code> directly, this tag
* avoids handling <code>null</code> and the incorrect type of
* <code>Context</code> in the <code>ContextHolder</code>. The tag also
* properly accommodates <code>Authentication.getPrincipal()</code>, which can
* either be a <code>String</code> or a <code>UserDetails</code>.
* Whilst JSPs can access the <code>SecurityContext</code> directly, this tag
* avoids handling <code>null</code> conditions. The tag also properly
* accommodates <code>Authentication.getPrincipal()</code>, which can either
* be a <code>String</code> or a <code>UserDetails</code>.
* </p>
*
* @author Ben Alex
@ -70,14 +68,11 @@ public class AuthenticationTag extends TagSupport {
throw new JspException("Unsupported use of auth:authentication tag");
}
if ((ContextHolder.getContext() == null)
|| !(ContextHolder.getContext() instanceof SecureContext)
|| (((SecureContext) ContextHolder.getContext()).getAuthentication() == null)) {
if (SecurityContext.getAuthentication() == null) {
return Tag.SKIP_BODY;
}
Authentication auth = ((SecureContext) ContextHolder.getContext())
.getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
if (auth.getPrincipal() == null) {
return Tag.SKIP_BODY;

View File

@ -18,8 +18,7 @@ package net.sf.acegisecurity.taglibs.authz;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import org.springframework.util.StringUtils;
@ -123,13 +122,7 @@ public class AuthorizeTag extends TagSupport {
}
private Collection getPrincipalAuthorities() {
SecureContext context = ((SecureContext) ContextHolder.getContext());
if (null == context) {
return Collections.EMPTY_LIST;
}
Authentication currentUser = context.getAuthentication();
Authentication currentUser = SecurityContext.getAuthentication();
if (null == currentUser) {
return Collections.EMPTY_LIST;

View File

@ -18,9 +18,7 @@ package net.sf.acegisecurity.ui;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.AuthenticationManager;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.ui.rememberme.NullRememberMeServices;
import net.sf.acegisecurity.ui.rememberme.RememberMeServices;
@ -46,8 +44,8 @@ import javax.servlet.http.HttpServletResponse;
* <p>
* This filter is responsible for processing authentication requests. If
* authentication is successful, the resulting {@link Authentication} object
* will be placed into the <code>ContextHolder</code>, which is guaranteed to
* have already been created by an earlier filter.
* will be placed into the <code>SecurityContext</code>, which is guaranteed
* to have already been created by an earlier filter.
* </p>
*
* <p>
@ -249,10 +247,13 @@ public abstract class AbstractProcessingFilter implements Filter,
}
public void afterPropertiesSet() throws Exception {
Assert.hasLength(filterProcessesUrl, "filterProcessesUrl must be specified");
Assert.hasLength(filterProcessesUrl,
"filterProcessesUrl must be specified");
Assert.hasLength(defaultTargetUrl, "defaultTargetUrl must be specified");
Assert.hasLength(authenticationFailureUrl, "authenticationFailureUrl must be specified");
Assert.notNull(authenticationManager, "authenticationManager must be specified");
Assert.hasLength(authenticationFailureUrl,
"authenticationFailureUrl must be specified");
Assert.notNull(authenticationManager,
"authenticationManager must be specified");
Assert.notNull(this.rememberMeServices);
}
@ -329,10 +330,13 @@ public abstract class AbstractProcessingFilter implements Filter,
* Indicates whether this filter should attempt to process a login request
* for the current invocation.
* </p>
*
* <p>
* It strips any parameters from the "path" section of the request URL (such as the
* jsessionid parameter in <em>http://host/myapp/index.html;jsessionid=blah</em>)
* before matching against the <code>filterProcessesUrl</code> property.
* It strips any parameters from the "path" section of the request URL
* (such as the jsessionid parameter in
* <em>http://host/myapp/index.html;jsessionid=blah</em>) before matching
* against the <code>filterProcessesUrl</code> property.
* </p>
*
* <p>
* Subclasses may override for special requirements, such as Tapestry
@ -350,7 +354,7 @@ public abstract class AbstractProcessingFilter implements Filter,
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');
if(pathParamIndex > 0) {
if (pathParamIndex > 0) {
// strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex);
}
@ -365,8 +369,7 @@ public abstract class AbstractProcessingFilter implements Filter,
logger.debug("Authentication success: " + authResult.toString());
}
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(authResult);
SecurityContext.setAuthentication(authResult);
if (logger.isDebugEnabled()) {
logger.debug(
@ -401,9 +404,7 @@ public abstract class AbstractProcessingFilter implements Filter,
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException {
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(null);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug("Updated ContextHolder to contain null Authentication");

View File

@ -18,9 +18,7 @@ package net.sf.acegisecurity.ui.basicauth;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.AuthenticationManager;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.intercept.web.AuthenticationEntryPoint;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.ui.WebAuthenticationDetails;
@ -30,6 +28,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.io.IOException;
@ -133,8 +132,10 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.authenticationManager, "An AuthenticationManager is required");
Assert.notNull(this.authenticationEntryPoint, "An AuthenticationEntryPoint is required");
Assert.notNull(this.authenticationManager,
"An AuthenticationManager is required");
Assert.notNull(this.authenticationEntryPoint,
"An AuthenticationEntryPoint is required");
}
public void destroy() {}
@ -176,7 +177,6 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
authRequest.setDetails(new WebAuthenticationDetails(httpRequest));
Authentication authResult;
SecureContext sc = SecureContextUtils.getSecureContext();
try {
authResult = authenticationManager.authenticate(authRequest);
@ -187,8 +187,7 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
+ " failed: " + failed.toString());
}
sc.setAuthentication(null);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(null);
authenticationEntryPoint.commence(request, response, failed);
return;
@ -199,8 +198,7 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
logger.debug("Authentication success: " + authResult.toString());
}
sc.setAuthentication(authResult);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(authResult);
}
chain.doFilter(request, response);

View File

@ -15,15 +15,11 @@
package net.sf.acegisecurity.ui.digestauth;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.AuthenticationServiceException;
import net.sf.acegisecurity.BadCredentialsException;
import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.intercept.web.AuthenticationEntryPoint;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.dao.AuthenticationDao;
import net.sf.acegisecurity.providers.dao.UserCache;
@ -39,8 +35,8 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.IOException;
@ -140,7 +136,8 @@ public class DigestProcessingFilter implements Filter, InitializingBean {
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationDao, "An AuthenticationDao is required");
Assert.notNull(authenticationEntryPoint, "A DigestProcessingFilterEntryPoint is required");
Assert.notNull(authenticationEntryPoint,
"A DigestProcessingFilterEntryPoint is required");
}
public void destroy() {}
@ -374,9 +371,7 @@ public class DigestProcessingFilter implements Filter, InitializingBean {
user.getPassword());
authRequest.setDetails(new WebAuthenticationDetails(httpRequest));
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(authRequest);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(authRequest);
}
chain.doFilter(request, response);
@ -441,9 +436,7 @@ public class DigestProcessingFilter implements Filter, InitializingBean {
private void fail(ServletRequest request, ServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(null);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug(failed);

View File

@ -15,6 +15,15 @@
package net.sf.acegisecurity.ui.rememberme;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.io.IOException;
import javax.servlet.Filter;
@ -26,18 +35,10 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
* Detects if there is no <code>Authentication</code> object in the
* <code>ContextHolder</code>, and populates it with a remember-me
* <code>SecurityContext</code>, and populates it with a remember-me
* authentication token if a {@link
* net.sf.acegisecurity.ui.rememberme.RememberMeServices} implementation so
* requests.
@ -48,7 +49,7 @@ import org.springframework.util.Assert;
* net.sf.acegisecurity.ui.rememberme.RememberMeServices#autoLogin(HttpServletRequest,
* HttpServletResponse)} method called by this filter. The
* <code>Authentication</code> or <code>null</code> returned by that method
* will be placed into the <code>ContextHolder</code>.
* will be placed into the <code>SecurityContext</code>.
* </p>
*
* <P>
@ -71,6 +72,14 @@ public class RememberMeProcessingFilter implements Filter, InitializingBean {
//~ Methods ================================================================
public void setRememberMeServices(RememberMeServices rememberMeServices) {
this.rememberMeServices = rememberMeServices;
}
public RememberMeServices getRememberMeServices() {
return rememberMeServices;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(rememberMeServices);
}
@ -93,21 +102,19 @@ public class RememberMeProcessingFilter implements Filter, InitializingBean {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
SecureContext sc = SecureContextUtils.getSecureContext();
if (sc.getAuthentication() == null) {
sc.setAuthentication(rememberMeServices.autoLogin(httpRequest,
httpResponse));
if (SecurityContext.getAuthentication() == null) {
SecurityContext.setAuthentication(rememberMeServices.autoLogin(
httpRequest, httpResponse));
if (logger.isDebugEnabled()) {
logger.debug("Replaced ContextHolder with remember-me token: '"
+ sc.getAuthentication() + "'");
+ SecurityContext.getAuthentication() + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"ContextHolder not replaced with remember-me token, as ContextHolder already contained: '"
+ sc.getAuthentication() + "'");
+ SecurityContext.getAuthentication() + "'");
}
}
@ -122,10 +129,4 @@ public class RememberMeProcessingFilter implements Filter, InitializingBean {
* @throws ServletException not thrown
*/
public void init(FilterConfig arg0) throws ServletException {}
public RememberMeServices getRememberMeServices() {
return rememberMeServices;
}
public void setRememberMeServices(RememberMeServices rememberMeServices) {
this.rememberMeServices = rememberMeServices;
}
}

View File

@ -15,40 +15,45 @@
package net.sf.acegisecurity.ui.x509;
import net.sf.acegisecurity.ui.AbstractProcessingFilter;
import net.sf.acegisecurity.ui.WebAuthenticationDetails;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.AuthenticationManager;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.x509.X509AuthenticationToken;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import java.security.cert.X509Certificate;
import java.io.IOException;
import net.sf.acegisecurity.ui.AbstractProcessingFilter;
import net.sf.acegisecurity.ui.WebAuthenticationDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.io.IOException;
import java.security.cert.X509Certificate;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Processes the X.509 certificate submitted by a client browser
* when HTTPS is used with client-authentication enabled.
* Processes the X.509 certificate submitted by a client browser when HTTPS is
* used with client-authentication enabled.
*
* <p>
* An {@link X509AuthenticationToken} is created with the certificate
* as the credentials.
* An {@link X509AuthenticationToken} is created with the certificate as the
* credentials.
* </p>
*
* <p>
* The configured authentication manager is expected to supply a
* provider which can handle this token (usually an instance of
* {@link net.sf.acegisecurity.providers.x509.X509AuthenticationProvider}).
* The configured authentication manager is expected to supply a provider which
* can handle this token (usually an instance of {@link
* net.sf.acegisecurity.providers.x509.X509AuthenticationProvider}).
* </p>
*
*
* <p>
* <b>Do not use this class directly.</b> Instead configure
* <code>web.xml</code> to use the {@link
@ -69,17 +74,22 @@ public class X509ProcessingFilter implements Filter, InitializingBean {
//~ Methods ================================================================
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
public void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "An AuthenticationManager must be set");
Assert.notNull(authenticationManager,
"An AuthenticationManager must be set");
}
public void destroy() {}
/**
* This method first checks for an existing, non-null authentication in the
* secure context. If one is found it does nothing.
*
* <p>
* If no authentication object exists, it attempts to obtain the client
* authentication certificate from the request. If there is no certificate
@ -87,13 +97,22 @@ public class X509ProcessingFilter implements Filter, InitializingBean {
* request containing the certificate will be passed to the configured
* {@link AuthenticationManager}.
* </p>
*
* <p>
* If authentication is successful the returned token will be stored in
* the secure context. Otherwise it will be set to null.
* In either case, the request proceeds through the filter chain.
* If authentication is successful the returned token will be stored in the
* secure context. Otherwise it will be set to null. In either case, the
* request proceeds through the filter chain.
* </p>
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param filterChain DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
* @throws ServletException DOCUMENT ME!
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
@ -105,12 +124,12 @@ public class X509ProcessingFilter implements Filter, InitializingBean {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
SecureContext ctx = SecureContextUtils.getSecureContext();
logger.debug("Checking secure context token: " + ctx.getAuthentication());
if (ctx.getAuthentication() == null) {
if (logger.isDebugEnabled()) {
logger.debug("Checking secure context token: "
+ SecurityContext.getAuthentication());
}
if (SecurityContext.getAuthentication() == null) {
Authentication authResult = null;
X509Certificate clientCertificate = extractClientCertificate(httpRequest);
@ -124,13 +143,57 @@ public class X509ProcessingFilter implements Filter, InitializingBean {
unsuccessfulAuthentication(httpRequest, httpResponse, failed);
}
}
filterChain.doFilter(request, response);
}
private X509Certificate extractClientCertificate(HttpServletRequest request) {
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
public void init(FilterConfig filterConfig) throws ServletException {}
if (certs != null && certs.length > 0) {
/**
* Puts the <code>Authentication</code> instance returned by the
* authentication manager into the secure context.
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param authResult DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response, Authentication authResult)
throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult);
}
SecurityContext.setAuthentication(authResult);
}
/**
* Ensures the authentication object in the secure context is set to null
* when authentication fails.
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
* @param failed DOCUMENT ME!
*/
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed) {
SecurityContext.setAuthentication(null);
if (logger.isDebugEnabled()) {
logger.debug("Updated ContextHolder to contain null Authentication");
}
request.getSession().setAttribute(AbstractProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY,
failed);
}
private X509Certificate extractClientCertificate(HttpServletRequest request) {
X509Certificate[] certs = (X509Certificate[]) request.getAttribute(
"javax.servlet.request.X509Certificate");
if ((certs != null) && (certs.length > 0)) {
return certs[0];
}
@ -140,40 +203,4 @@ public class X509ProcessingFilter implements Filter, InitializingBean {
return null;
}
/**
* Puts the <code>Authentication</code> instance returned by the authentication manager into
* the secure context.
*/
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult)
throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult);
}
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(authResult);
}
/**
* Ensures the authentication object in the secure context is set to null when authentication fails.
*
*/
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(null);
ContextHolder.setContext(sc);
if (logger.isDebugEnabled()) {
logger.debug("Updated ContextHolder to contain null Authentication");
}
request.getSession().setAttribute(AbstractProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY, failed);
}
public void init(FilterConfig filterConfig) throws ServletException { }
public void destroy() { }
}

View File

@ -18,11 +18,8 @@ package net.sf.acegisecurity.wrapper;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationTrustResolver;
import net.sf.acegisecurity.AuthenticationTrustResolverImpl;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import java.security.Principal;
@ -32,7 +29,7 @@ import javax.servlet.http.HttpServletRequestWrapper;
/**
* An Acegi Security-aware <code>HttpServletRequestWrapper</code>, which uses
* the <code>ContextHolder</code>-defined <code>Authentication</code> object
* the <code>SecurityContext</code>-defined <code>Authentication</code> object
* for {@link ContextHolderAwareRequestWrapper#isUserInRole(java.lang.String)}
* and {@link javax.servlet.http.HttpServletRequestWrapper#getRemoteUser()}
* responses.
@ -113,15 +110,16 @@ public class ContextHolderAwareRequestWrapper extends HttpServletRequestWrapper
return auth;
}
/**
* Obtain the current active <code>Authentication</code>
*
* @return the authentication object or <code>null</code>
*/
private Authentication getAuthentication() {
if ((ContextHolder.getContext() != null)
&& ContextHolder.getContext() instanceof SecureContext) {
Authentication auth = SecureContextUtils.getSecureContext()
.getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
if (!authenticationTrustResolver.isAnonymous(auth)) {
return auth;
}
if (!authenticationTrustResolver.isAnonymous(auth)) {
return auth;
}
return null;

View File

@ -15,9 +15,7 @@
package net.sf.acegisecurity;
import net.sf.acegisecurity.context.Context;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
/**
@ -44,24 +42,18 @@ public class TargetObject implements ITargetObject {
* @param input the message to make lowercase
*
* @return the lowercase message, a space, the <code>Authentication</code>
* class that was on the <code>ContextHolder</code> at the time of
* method invocation, and a boolean indicating if the
* class that was on the <code>SecurityContext</code> at the time
* of method invocation, and a boolean indicating if the
* <code>Authentication</code> object is authenticated or not
*/
public String makeLowerCase(String input) {
Context context = ContextHolder.getContext();
Authentication auth = SecurityContext.getAuthentication();
if ((context != null) && (context instanceof SecureContext)) {
Authentication auth = ((SecureContext) context).getAuthentication();
if (auth == null) {
return input.toLowerCase() + " Authentication empty";
} else {
return input.toLowerCase() + " " + auth.getClass().getName()
+ " " + auth.isAuthenticated();
}
if (auth == null) {
return input.toLowerCase() + " Authentication empty";
} else {
return input.toLowerCase() + " ContextHolder Not Security Aware";
return input.toLowerCase() + " " + auth.getClass().getName() + " "
+ auth.isAuthenticated();
}
}
@ -72,23 +64,12 @@ public class TargetObject implements ITargetObject {
* @param input the message to make uppercase
*
* @return the uppercase message, a space, the <code>Authentication</code>
* class that was on the <code>ContextHolder</code> at the time of
* method invocation, and a boolean indicating if the
* class that was on the <code>SecurityContext</code> at the time
* of method invocation, and a boolean indicating if the
* <code>Authentication</code> object is authenticated or not
*
* @throws AccessDeniedException if for some reason this method was being
* called and the <code>ContextHolder</code> was <code>null</code>
* or did not hold a <code>SecureContext</code>
*/
public String makeUpperCase(String input) {
Context context = ContextHolder.getContext();
if ((context == null) || !(context instanceof SecureContext)) {
throw new AccessDeniedException(
"For some reason the SecurityInterceptor allowed this call, meaning the ContextHolder should have been populated, but it was not.");
}
Authentication auth = ((SecureContext) context).getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
return input.toUpperCase() + " " + auth.getClass().getName() + " "
+ auth.isAuthenticated();

View File

@ -19,10 +19,9 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.util.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@ -58,17 +57,19 @@ public class HttpRequestIntegrationFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setUserPrincipal(principal);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain(true);
filter.doFilter(request, response, chain);
if (!(SecureContextUtils.getSecureContext().getAuthentication() instanceof PrincipalAcegiUserToken)) {
if (!(SecurityContext.getAuthentication() instanceof PrincipalAcegiUserToken)) {
System.out.println(SecurityContext.getAuthentication());
fail("Should have returned PrincipalAcegiUserToken");
}
PrincipalAcegiUserToken castResult = (PrincipalAcegiUserToken) SecureContextUtils.getSecureContext()
.getAuthentication();
PrincipalAcegiUserToken castResult = (PrincipalAcegiUserToken) SecurityContext
.getAuthentication();
assertEquals(principal, castResult);
}
@ -90,18 +91,18 @@ public class HttpRequestIntegrationFilterTests extends TestCase {
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain(true);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
filter.doFilter(request, response, chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -1,80 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
import junit.framework.TestCase;
/**
* Tests {@link ContextHolder}.
*
* @author Ben Alex
* @version $Id$
*/
public class ContextHolderTests extends TestCase {
//~ Constructors ===========================================================
public ContextHolderTests() {
super();
}
public ContextHolderTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public void tearDown() {
ContextHolder.setContext(null);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(ContextHolderTests.class);
}
public void testContextHolderGetterSetter() {
assertEquals(null, ContextHolder.getContext());
MockContext context = new MockContext();
context.setColour("red");
ContextHolder.setContext(context);
MockContext offContext = (MockContext) ContextHolder.getContext();
assertEquals("red", offContext.getColour());
}
//~ Inner Classes ==========================================================
private class MockContext implements Context {
private String colour;
public void setColour(String colour) {
this.colour = colour;
}
public String getColour() {
return colour;
}
public void validate() throws ContextInvalidException {
return;
}
}
}

View File

@ -1,108 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
import junit.framework.TestCase;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import java.util.Properties;
/**
* Tests {@link ContextInterceptor}.
*
* @author Ben Alex
* @version $Id$
*/
public class ContextInterceptorTests extends TestCase {
//~ Constructors ===========================================================
public ContextInterceptorTests() {
super();
}
public ContextInterceptorTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(ContextInterceptorTests.class);
}
public ITargetObject makeInterceptedTarget() {
String PREFIX = "beans.";
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
Properties p = new Properties();
p.setProperty(PREFIX + "contextInterceptor.class",
"net.sf.acegisecurity.context.ContextInterceptor");
p.setProperty(PREFIX + "targetObject.class",
"net.sf.acegisecurity.context.TargetObject");
p.setProperty(PREFIX + "target.class",
"org.springframework.aop.framework.ProxyFactoryBean");
p.setProperty(PREFIX + "target.proxyInterfaces",
"net.sf.acegisecurity.context.ITargetObject");
p.setProperty(PREFIX + "target.interceptorNames",
"contextInterceptor,targetObject");
int count = (new PropertiesBeanDefinitionReader(lbf))
.registerBeanDefinitions(p, PREFIX);
return (ITargetObject) lbf.getBean("target");
}
public void testInterceptorDetectsEmptyContextHolder()
throws Exception {
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("hello");
fail("Should have thrown ContextHolderEmptyException");
} catch (ContextHolderEmptyException expected) {
assertTrue(true);
}
}
public void testInterceptorDetectsInvalidContext()
throws Exception {
ITargetObject target = makeInterceptedTarget();
ContextHolder.setContext(new SecureContextImpl()); // Authentication not set
try {
target.makeUpperCase("hello");
fail("Should have thrown ContextInvalidException");
} catch (ContextInvalidException expected) {
assertTrue(true);
}
}
public void testInterceptorNormalOperation() throws Exception {
ITargetObject target = makeInterceptedTarget();
ContextHolder.setContext(new ContextImpl());
String result = target.makeUpperCase("hello");
assertEquals("HELLO", result);
}
}

View File

@ -23,9 +23,9 @@ import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.MockFilterConfig;
import net.sf.acegisecurity.adapters.PrincipalAcegiUserToken;
import net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
@ -36,10 +36,6 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests {@link HttpSessionContextIntegrationFilter}.
@ -64,26 +60,6 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
junit.textui.TestRunner.run(HttpSessionContextIntegrationFilterTests.class);
}
public void testDetectsMissingOrInvalidContext() throws Exception {
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
try {
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
filter.setContext(Integer.class);
assertEquals(Integer.class, filter.getContext());
filter.afterPropertiesSet();
fail("Shown have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testExistingContextContentsCopiedIntoContextHolderFromSessionAndChangesToContextCopiedBackToSession()
throws Exception {
// Build an Authentication object we simulate came from HttpSession
@ -96,15 +72,10 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
"someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")});
// Build a Context to store in HttpSession (simulating prior request)
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(sessionPrincipal);
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY,
sc);
request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY,
sessionPrincipal);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(sessionPrincipal,
@ -112,17 +83,15 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContext(SecureContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Obtain new/update Authentication from HttpSession
Context context = (Context) request.getSession().getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal,
((SecureContext) context).getAuthentication());
Authentication auth = (Authentication) request.getSession()
.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY);
assertEquals(updatedPrincipal, auth);
}
public void testHttpSessionCreatedWhenContextHolderChanges()
@ -139,16 +108,15 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContext(SecureContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Obtain new/update Authentication from HttpSession
Context context = (Context) request.getSession(false).getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal, ((SecureContext) context).getAuthentication());
Authentication auth = (Authentication) request.getSession(false)
.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY);
assertEquals(updatedPrincipal, auth);
}
public void testHttpSessionNotCreatedUnlessContextHolderChanges()
@ -160,8 +128,6 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContext(SecureContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
@ -179,26 +145,24 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_DIFFERENT_ROLE")});
// Build a mock request
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY,
request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY,
"NOT_A_CONTEXT_OBJECT");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(null, updatedPrincipal);
// Prepare filter
HttpSessionContextIntegrationFilter filter = new HttpSessionContextIntegrationFilter();
filter.setContext(SecureContextImpl.class);
filter.afterPropertiesSet();
// Execute filter
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, response, chain);
// Obtain new/update Authentication from HttpSession
Context context = (Context) request.getSession().getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);
assertEquals(updatedPrincipal,
((SecureContext) context).getAuthentication());
Authentication auth = (Authentication) request.getSession()
.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_AUTHENTICATION_CONTEXT_KEY);
assertEquals(updatedPrincipal, auth);
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
@ -227,13 +191,11 @@ public class HttpSessionContextIntegrationFilterTests extends TestCase {
throws IOException, ServletException {
if (expectedOnContextHolder != null) {
assertEquals(expectedOnContextHolder,
SecureContextUtils.getSecureContext().getAuthentication());
SecurityContext.getAuthentication());
}
if (changeContextHolder != null) {
SecureContext sc = SecureContextUtils.getSecureContext();
sc.setAuthentication(changeContextHolder);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(changeContextHolder);
}
}
}

View File

@ -1,28 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
/**
* Represents the interface of a secured object.
*
* @author Ben Alex
* @version $Id$
*/
public interface ITargetObject {
//~ Methods ================================================================
public String makeUpperCase(String input);
}

View File

@ -1,93 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
/**
* Tests {@link SecureContextImpl}.
*
* @author Ben Alex
* @version $Id$
*/
public class SecureContextImplTests extends TestCase {
//~ Constructors ===========================================================
public SecureContextImplTests() {
super();
}
public SecureContextImplTests(String arg0) {
super(arg0);
}
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SecureContextImplTests.class);
}
public void testEmptyObjectsAreEquals() {
SecureContextImpl obj1 = new SecureContextImpl();
SecureContextImpl obj2 = new SecureContextImpl();
assertTrue(obj1.equals(obj2));
}
public void testSecureContextCorrectOperation() {
SecureContext context = new SecureContextImpl();
Authentication auth = new UsernamePasswordAuthenticationToken("marissa",
"koala");
context.setAuthentication(auth);
context.validate();
assertEquals(auth, context.getAuthentication());
assertTrue(context.toString().lastIndexOf("marissa") != -1);
}
public void testSecureContextDetectsMissingAuthenticationObject() {
SecureContext context = new SecureContextImpl();
assertTrue(context.toString().lastIndexOf("Null authentication") != -1);
try {
context.validate();
fail("Should have thrown ContextInvalidException");
} catch (ContextInvalidException expected) {
assertTrue(true);
}
}
public void testSecureContextDetectsNullAuthenticationObject() {
SecureContext context = new SecureContextImpl();
context.setAuthentication(null);
try {
context.validate();
fail("Should have thrown ContextInvalidException");
} catch (ContextInvalidException expected) {
assertTrue(true);
}
}
}

View File

@ -1,4 +1,4 @@
/* Copyright 2004 Acegi Technology Pty Limited
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -17,21 +17,23 @@ package net.sf.acegisecurity.context;
import junit.framework.TestCase;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
/**
* Tests {@link ContextImpl}.
* Tests {@link SecurityContext}.
*
* @author Ben Alex
* @version $Id$
*/
public class ContextImplTests extends TestCase {
public class SecurityContextTests extends TestCase {
//~ Constructors ===========================================================
public ContextImplTests() {
public SecurityContextTests() {
super();
}
public ContextImplTests(String arg0) {
public SecurityContextTests(String arg0) {
super(arg0);
}
@ -42,12 +44,20 @@ public class ContextImplTests extends TestCase {
}
public static void main(String[] args) {
junit.textui.TestRunner.run(ContextImplTests.class);
junit.textui.TestRunner.run(SecurityContextTests.class);
}
public void testConfirmsContextImplHasTheValidateMethod() {
Context context = new ContextImpl();
context.validate();
assertTrue(true);
public void tearDown() {
SecurityContext.setAuthentication(null);
}
public void testContextHolderGetterSetter() {
assertEquals(null, SecurityContext.getAuthentication());
SecurityContext.setAuthentication(new UsernamePasswordAuthenticationToken(
"ben", "12345"));
assertEquals("12345",
SecurityContext.getAuthentication().getCredentials());
}
}

View File

@ -1,30 +0,0 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.acegisecurity.context;
/**
* Represents a secured object.
*
* @author Ben Alex
* @version $Id$
*/
public class TargetObject implements ITargetObject {
//~ Methods ================================================================
public String makeUpperCase(String input) {
return input.toUpperCase();
}
}

View File

@ -18,10 +18,8 @@ package net.sf.acegisecurity.context.httpinvoker;
import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.context.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import java.io.IOException;
@ -59,11 +57,9 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
public void testNormalOperation() throws Exception {
// Setup client-side context
SecureContext clientSideContext = new SecureContextImpl();
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("Aladdin",
"open sesame");
clientSideContext.setAuthentication(clientSideAuthentication);
ContextHolder.setContext(clientSideContext);
SecurityContext.setAuthentication(clientSideAuthentication);
// Create a connection and ensure our executor sets its
// properties correctly
@ -78,28 +74,11 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests
assertEquals("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
conn.getRequestProperty("Authorization"));
ContextHolder.setContext(null);
}
public void testNullAuthenticationIsNull() throws Exception {
// Setup client-side context
SecureContext clientSideContext = new SecureContextImpl();
clientSideContext.setAuthentication(null);
ContextHolder.setContext(clientSideContext);
// Create a connection and ensure our executor sets its
// properties correctly
AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor();
HttpURLConnection conn = new MockHttpURLConnection(new URL(
"http://localhost/"));
executor.prepareConnection(conn, 10);
// Check connection properties (shouldn't be an Authorization header)
assertNull(conn.getRequestProperty("Authorization"));
SecurityContext.setAuthentication(null);
}
public void testNullContextHolderIsNull() throws Exception {
ContextHolder.setContext(null); // just to be explicit
SecurityContext.setAuthentication(null);
// Create a connection and ensure our executor sets its
// properties correctly

View File

@ -20,11 +20,9 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.MockMethodInvocation;
import net.sf.acegisecurity.TargetObject;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.context.rmi.ContextPropagatingRemoteInvocation;
import net.sf.acegisecurity.context.rmi.ContextPropagatingRemoteInvocationFactory;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.aopalliance.intercept.MethodInvocation;
@ -58,18 +56,16 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
public void testNormalOperation() throws Exception {
// Setup client-side context
SecureContext clientSideContext = new SecureContextImpl();
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("marissa",
"koala");
clientSideContext.setAuthentication(clientSideAuthentication);
ContextHolder.setContext(clientSideContext);
SecurityContext.setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
// Set to null, as ContextPropagatingRemoteInvocation already obtained
// a copy and nulling is necessary to ensure the Context delivered by
// ContextPropagatingRemoteInvocation is used on server-side
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
// The result from invoking the TargetObject should contain the
// Authentication class delivered via the ContextHolder
@ -79,12 +75,12 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
public void testNullContextHolderDoesNotCauseInvocationProblems()
throws Exception {
ContextHolder.setContext(null); // just to be explicit
SecurityContext.setAuthentication(null); // just to be explicit
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
ContextHolder.setContext(null); // unnecessary, but for explicitness
SecurityContext.setAuthentication(null); // unnecessary, but for explicitness
assertEquals("some_string ContextHolder Not Security Aware",
assertEquals("some_string Authentication empty",
remoteInvocation.invoke(new TargetObject()));
}

View File

@ -27,9 +27,7 @@ import net.sf.acegisecurity.OtherTargetObject;
import net.sf.acegisecurity.SecurityConfig;
import net.sf.acegisecurity.TargetObject;
import net.sf.acegisecurity.acl.basic.SomeDomain;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.springframework.context.ApplicationContext;
@ -167,29 +165,25 @@ public class MethodDefinitionAttributesTests extends TestCase {
}
public void testMethodCallWithRunAsReplacement() throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_UPPER_CASE")});
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO net.sf.acegisecurity.MockRunAsAuthenticationToken true",
result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_INTERFACE_METHOD_MAKE_LOWER_CASE")});
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeLowerCase("HELLO");
@ -197,7 +191,7 @@ public class MethodDefinitionAttributesTests extends TestCase {
assertEquals("hello net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken true",
result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testNullReturnedIfZeroAttributesDefinedForMethodInvocation()

View File

@ -33,10 +33,7 @@ import net.sf.acegisecurity.MockAfterInvocationManager;
import net.sf.acegisecurity.MockAuthenticationManager;
import net.sf.acegisecurity.MockRunAsManager;
import net.sf.acegisecurity.RunAsManager;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.ContextImpl;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.intercept.method.AbstractMethodDefinitionSource;
import net.sf.acegisecurity.intercept.method.MockMethodDefinitionSource;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
@ -79,50 +76,34 @@ public class MethodSecurityInterceptorTests extends TestCase {
public void testCallingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts()
throws Exception {
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello ContextHolder Not Security Aware", result);
ContextHolder.setContext(null);
}
public void testCallingAPublicMethodWhenPresentingASecureContextButWithoutAnyAuthenticationObject()
throws Exception {
SecureContext context = new SecureContextImpl();
ContextHolder.setContext(context);
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello Authentication empty", result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testCallingAPublicMethodWhenPresentingAnAuthenticationObjectWillProperlySetItsIsAuthenticatedProperty()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_THIS_IS_NOT_REQUIRED_AS_IT_IS_PUBLIC")});
assertTrue(!token.isAuthenticated());
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.publicMakeLowerCase("HELLO");
assertEquals("hello net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken false",
result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testDeniesWhenAppropriate() throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_NO_BENEFIT_TO_THIS_GRANTED_AUTHORITY")});
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
@ -133,7 +114,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
assertTrue(true);
}
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testGetters() {
@ -159,30 +140,26 @@ public class MethodSecurityInterceptorTests extends TestCase {
}
public void testMethodCallWithRunAsReplacement() throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_UPPER")});
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTarget();
String result = target.makeUpperCase("hello");
assertEquals("HELLO net.sf.acegisecurity.MockRunAsAuthenticationToken true",
result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testMethodCallWithoutRunAsReplacement()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
assertTrue(!token.isAuthenticated());
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTargetWithoutAnAfterInvocationManager();
String result = target.makeLowerCase("HELLO");
@ -191,10 +168,10 @@ public class MethodSecurityInterceptorTests extends TestCase {
assertEquals("hello net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken true",
result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testRejectionOfEmptyContextHolder() throws Exception {
public void testRejectionOfEmptySecurityContext() throws Exception {
ITargetObject target = makeInterceptedTarget();
try {
@ -206,40 +183,6 @@ public class MethodSecurityInterceptorTests extends TestCase {
}
}
public void testRejectionOfNonSecureContextOnContextHolder()
throws Exception {
ContextHolder.setContext(new ContextImpl());
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("hello");
fail(
"Should have thrown AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException expected) {
assertTrue(true);
}
ContextHolder.setContext(null);
}
public void testRejectionOfSecureContextThatContainsNoAuthenticationObject()
throws Exception {
ContextHolder.setContext(new SecureContextImpl());
ITargetObject target = makeInterceptedTarget();
try {
target.makeUpperCase("hello");
fail(
"Should have thrown AuthenticationCredentialsNotFoundException");
} catch (AuthenticationCredentialsNotFoundException expected) {
assertTrue(true);
}
ContextHolder.setContext(null);
}
public void testRejectsAccessDecisionManagersThatDoNotSupportMethodInvocation()
throws Exception {
MethodSecurityInterceptor si = new MethodSecurityInterceptor();
@ -259,13 +202,11 @@ public class MethodSecurityInterceptorTests extends TestCase {
public void testRejectsCallsWhenAuthenticationIsIncorrect()
throws Exception {
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_LOWER")});
assertTrue(!token.isAuthenticated());
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
ITargetObject target = makeInterceptedTargetRejectsAuthentication();
@ -276,7 +217,7 @@ public class MethodSecurityInterceptorTests extends TestCase {
assertTrue(true);
}
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testRejectsCallsWhenObjectDefinitionSourceDoesNotSupportObject()

View File

@ -26,9 +26,7 @@ import net.sf.acegisecurity.MockAuthenticationManager;
import net.sf.acegisecurity.MockJoinPoint;
import net.sf.acegisecurity.MockRunAsManager;
import net.sf.acegisecurity.TargetObject;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.intercept.method.MethodDefinitionMap;
import net.sf.acegisecurity.intercept.method.MethodDefinitionSourceEditor;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
@ -88,17 +86,15 @@ public class AspectJSecurityInterceptorTests extends TestCase {
MockAspectJCallback aspectJCallback = new MockAspectJCallback();
SecureContext secureContext = new SecureContextImpl();
secureContext.setAuthentication(new TestingAuthenticationToken(
SecurityContext.setAuthentication(new TestingAuthenticationToken(
"marissa", "koala",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_ONE")}));
ContextHolder.setContext(secureContext);
Object result = si.invoke(joinPoint, aspectJCallback);
assertEquals("object proceeded", result);
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testCallbackIsNotInvokedWhenPermissionDenied()
@ -126,10 +122,8 @@ public class AspectJSecurityInterceptorTests extends TestCase {
MockAspectJCallback aspectJCallback = new MockAspectJCallback();
aspectJCallback.setThrowExceptionIfInvoked(true);
SecureContext secureContext = new SecureContextImpl();
secureContext.setAuthentication(new TestingAuthenticationToken(
SecurityContext.setAuthentication(new TestingAuthenticationToken(
"marissa", "koala", new GrantedAuthority[] {}));
ContextHolder.setContext(secureContext);
try {
si.invoke(joinPoint, aspectJCallback);
@ -138,7 +132,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
assertTrue(true);
}
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
//~ Inner Classes ==========================================================

View File

@ -30,11 +30,12 @@ import net.sf.acegisecurity.MockAuthenticationManager;
import net.sf.acegisecurity.MockRunAsManager;
import net.sf.acegisecurity.RunAsManager;
import net.sf.acegisecurity.SecurityConfig;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
@ -44,9 +45,6 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* Tests {@link FilterSecurityInterceptor}.
@ -169,19 +167,17 @@ public class FilterSecurityInterceptorTests extends TestCase {
request.setServerPort(443);
// Setup a Context
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_OK")});
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
// Create and test our secure object
FilterInvocation fi = new FilterInvocation(request, response, chain);
interceptor.invoke(fi);
// Destroy the Context
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testNormalStartupAndGetter() throws Exception {
@ -229,19 +225,17 @@ public class FilterSecurityInterceptorTests extends TestCase {
request.setServletPath("/secure/page.html");
// Setup a Context
SecureContext context = new SecureContextImpl();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test",
"Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("MOCK_OK")});
context.setAuthentication(token);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(token);
// Create and test our secure object
FilterInvocation fi = new FilterInvocation(request, response, chain);
interceptor.invoke(fi);
// Destroy the Context
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
//~ Inner Classes ==========================================================

View File

@ -17,10 +17,13 @@ package net.sf.acegisecurity.intercept.web;
import junit.framework.TestCase;
import net.sf.acegisecurity.*;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.AccessDeniedException;
import net.sf.acegisecurity.BadCredentialsException;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.MockAuthenticationEntryPoint;
import net.sf.acegisecurity.MockPortResolver;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter;
@ -80,11 +83,9 @@ public class SecurityEnforcementFilterTests extends TestCase {
false, false, false);
// Setup ContextHolder, as filter needs to check if user is anonymous
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(new AnonymousAuthenticationToken("ignored",
"ignored",
SecurityContext.setAuthentication(new AnonymousAuthenticationToken(
"ignored", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("IGNORED")}));
ContextHolder.setContext(sc);
// Test
SecurityEnforcementFilter filter = new SecurityEnforcementFilter();
@ -112,9 +113,7 @@ public class SecurityEnforcementFilterTests extends TestCase {
false, false, false);
// Setup ContextHolder, as filter needs to check if user is anonymous
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(null);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(null);
// Test
SecurityEnforcementFilter filter = new SecurityEnforcementFilter();
@ -357,7 +356,7 @@ public class SecurityEnforcementFilterTests extends TestCase {
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
//~ Inner Classes ==========================================================

View File

@ -21,16 +21,13 @@ import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.MockFilterConfig;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import net.sf.acegisecurity.providers.dao.memory.UserAttribute;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
@ -40,9 +37,6 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests {@link AnonymousProcessingFilter}.
@ -112,12 +106,10 @@ public class AnonymousProcessingFilterTests extends TestCase {
public void testOperationWhenAuthenticationExistsInContextHolder()
throws Exception {
// Put an Authentication object into the ContextHolder
SecureContext sc = SecureContextUtils.getSecureContext();
Authentication originalAuth = new TestingAuthenticationToken("user",
"password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
sc.setAuthentication(originalAuth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(originalAuth);
// Setup our filter correctly
UserAttribute user = new UserAttribute();
@ -133,12 +125,10 @@ public class AnonymousProcessingFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(),
new MockFilterChain(true));
request, new MockHttpServletResponse(), new MockFilterChain(true));
// Ensure filter didn't change our original object
assertEquals(originalAuth,
SecureContextUtils.getSecureContext().getAuthentication());
assertEquals(originalAuth, SecurityContext.getAuthentication());
}
public void testOperationWhenNoAuthenticationInContextHolder()
@ -155,11 +145,9 @@ public class AnonymousProcessingFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(),
new MockFilterChain(true));
request, new MockHttpServletResponse(), new MockFilterChain(true));
Authentication auth = SecureContextUtils.getSecureContext()
.getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
assertEquals("anonymousUsername", auth.getPrincipal());
assertEquals(new GrantedAuthorityImpl("ROLE_ANONYMOUS"),
auth.getAuthorities()[0]);
@ -167,12 +155,12 @@ public class AnonymousProcessingFilterTests extends TestCase {
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,

View File

@ -17,10 +17,7 @@ package net.sf.acegisecurity.providers.jaas;
import junit.framework.TestCase;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.ContextImpl;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import java.util.HashSet;
@ -40,69 +37,66 @@ public class SecureContextLoginModuleTest extends TestCase {
private SecureContextLoginModule module = null;
private Subject subject = new Subject(false, new HashSet(), new HashSet(),
new HashSet());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal", "credentials");
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal",
"credentials");
//~ Methods ================================================================
public void testAbort() throws Exception {
assertFalse("Should return false, no auth is set", module.abort());
SecurityContext.setAuthentication(auth);
module.login();
module.commit();
assertTrue(module.abort());
}
public void testLoginException() throws Exception {
try {
module.login();
fail("LoginException expected, there is no Authentication in the SecureContext");
} catch (LoginException e) {
}
fail(
"LoginException expected, there is no Authentication in the SecureContext");
} catch (LoginException e) {}
}
public void testLoginSuccess() throws Exception {
SecureContext sc = (SecureContext) ContextHolder.getContext();
sc.setAuthentication(auth);
assertTrue("Login should succeed, there is an authentication set", module.login());
assertTrue("The authentication is not null, this should return true", module.commit());
assertTrue("Principals should contain the authentication", subject.getPrincipals().contains(auth));
}
public void testNoContext() throws Exception {
ContextHolder.setContext(null);
assertFalse("Should return false and ask to be ignored", module.login());
}
public void testUnsupportedContext() throws Exception {
ContextHolder.setContext(new ContextImpl());
assertFalse("Should return false and ask to be ignored", module.login());
SecurityContext.setAuthentication(auth);
assertTrue("Login should succeed, there is an authentication set",
module.login());
assertTrue("The authentication is not null, this should return true",
module.commit());
assertTrue("Principals should contain the authentication",
subject.getPrincipals().contains(auth));
}
public void testLogout() throws Exception {
SecureContext sc = (SecureContext) ContextHolder.getContext();
sc.setAuthentication(auth);
SecurityContext.setAuthentication(auth);
module.login();
assertTrue("Should return true as it succeeds", module.logout());
assertEquals("Authentication should be null", null, module.getAuthentication());
assertEquals("Authentication should be null", null,
module.getAuthentication());
assertFalse("Principals should not contain the authentication after logout", subject.getPrincipals().contains(auth));
assertFalse("Principals should not contain the authentication after logout",
subject.getPrincipals().contains(auth));
}
public void testNullAuthenticationInSecureContext()
throws Exception {
SecurityContext.setAuthentication(null);
assertFalse("Should return false and ask to be ignored", module.login());
}
public void testNullLogout() throws Exception {
assertFalse(module.logout());
}
public void testAbort() throws Exception {
assertFalse("Should return false, no auth is set", module.abort());
SecureContext sc = (SecureContext) ContextHolder.getContext();
sc.setAuthentication(auth);
module.login();
module.commit();
assertTrue(module.abort());
}
protected void setUp() throws Exception {
module = new SecureContextLoginModule();
module.initialize(subject, null, null, null);
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
module = null;
}
}

View File

@ -25,9 +25,7 @@ import net.sf.acegisecurity.acl.AclEntry;
import net.sf.acegisecurity.acl.AclManager;
import net.sf.acegisecurity.acl.basic.MockAclObjectIdentity;
import net.sf.acegisecurity.acl.basic.SimpleAclEntry;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import org.springframework.context.ApplicationContext;
@ -55,64 +53,34 @@ public class AclTagTests extends TestCase {
throws JspException {
Authentication auth = new TestingAuthenticationToken("marissa",
"koala", new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION)
.toString());
aclTag.setDomainObject(new Integer(54));
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
ContextHolder.setContext(null);
}
public void testInclusionDeniedWhenAuthenticationEmpty()
throws JspException {
ContextHolder.setContext(new SecureContextImpl());
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION)
.toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
ContextHolder.setContext(null);
}
public void testInclusionDeniedWhenContextHolderEmpty()
throws JspException {
ContextHolder.setContext(null);
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION)
.toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testInclusionDeniedWhenNoListOfPermissionsGiven()
throws JspException {
Authentication auth = new TestingAuthenticationToken("marissa",
"koala", new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission(null);
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testInclusionDeniedWhenPrincipalDoesNotHoldAnyPermissions()
throws JspException {
Authentication auth = new TestingAuthenticationToken("john", "crow",
new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.ADMINISTRATION)
+ "," + new Integer(SimpleAclEntry.READ));
@ -122,22 +90,32 @@ public class AclTagTests extends TestCase {
assertEquals("object1", aclTag.getDomainObject());
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testInclusionDeniedWhenPrincipalDoesNotHoldRequiredPermissions()
throws JspException {
Authentication auth = new TestingAuthenticationToken("marissa",
"koala", new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.DELETE).toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testInclusionDeniedWhenSecurityContextEmpty()
throws JspException {
SecurityContext.setAuthentication(null);
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION)
.toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
SecurityContext.setAuthentication(null);
}
public void testInclusionPermittedWhenDomainObjectIsNull()
@ -151,9 +129,7 @@ public class AclTagTests extends TestCase {
throws JspException {
Authentication auth = new TestingAuthenticationToken("john", "crow",
new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission("0,5, 6"); // shouldn't be any space
@ -164,38 +140,34 @@ public class AclTagTests extends TestCase {
assertTrue(true);
}
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testOperationWhenPrincipalHoldsPermissionOfMultipleList()
throws JspException {
Authentication auth = new TestingAuthenticationToken("marissa",
"koala", new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.ADMINISTRATION)
+ "," + new Integer(SimpleAclEntry.READ));
aclTag.setDomainObject("object1");
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testOperationWhenPrincipalHoldsPermissionOfSingleList()
throws JspException {
Authentication auth = new TestingAuthenticationToken("marissa",
"koala", new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.READ).toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
//~ Inner Classes ==========================================================

View File

@ -19,9 +19,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import net.sf.acegisecurity.providers.dao.User;
@ -42,32 +40,10 @@ public class AuthenticationTagTests extends TestCase {
//~ Methods ================================================================
public void testOperationWhenAuthenticationIsNull()
throws JspException {
ContextHolder.setContext(new SecureContextImpl());
authenticationTag.setOperation("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(null, authenticationTag.getLastMessage());
ContextHolder.setContext(null);
}
public void testOperationWhenContextHolderIsNull()
throws JspException {
ContextHolder.setContext(null);
authenticationTag.setOperation("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(null, authenticationTag.getLastMessage());
}
public void testOperationWhenPrincipalIsAString() throws JspException {
Authentication auth = new TestingAuthenticationToken("marissaAsString",
"koala", new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
authenticationTag.setOperation("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
@ -80,9 +56,7 @@ public class AuthenticationTagTests extends TestCase {
"marissaUserDetails", "koala", true, true, true, true,
new GrantedAuthority[] {}), "koala",
new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
authenticationTag.setOperation("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
@ -92,14 +66,23 @@ public class AuthenticationTagTests extends TestCase {
public void testOperationWhenPrincipalIsNull() throws JspException {
Authentication auth = new TestingAuthenticationToken(null, "koala",
new GrantedAuthority[] {});
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
authenticationTag.setOperation("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
}
public void testOperationWhenSecurityContextIsNull()
throws JspException {
SecurityContext.setAuthentication(null);
authenticationTag.setOperation("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(null, authenticationTag.getLastMessage());
SecurityContext.setAuthentication(null);
}
public void testSkipsBodyIfNullOrEmptyOperation() throws Exception {
authenticationTag.setOperation("");
assertEquals("", authenticationTag.getOperation());

View File

@ -19,8 +19,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
@ -37,7 +36,6 @@ public class AuthorizeTagAttributeTests extends TestCase {
//~ Instance fields ========================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private SecureContextImpl context;
private TestingAuthenticationToken currentUser;
//~ Methods ================================================================
@ -95,13 +93,10 @@ public class AuthorizeTagAttributeTests extends TestCase {
"ROLE_SUPERVISOR"), new GrantedAuthorityImpl(
"ROLE_RESTRICTED"),});
context = new SecureContextImpl();
context.setAuthentication(currentUser);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -18,8 +18,7 @@ package net.sf.acegisecurity.taglibs.authz;
import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
@ -36,7 +35,6 @@ public class AuthorizeTagCustomGrantedAuthorityTests extends TestCase {
//~ Instance fields ========================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private SecureContextImpl context;
private TestingAuthenticationToken currentUser;
//~ Methods ================================================================
@ -51,7 +49,8 @@ public class AuthorizeTagCustomGrantedAuthorityTests extends TestCase {
public void testRejectsRequestWhenCustomAuthorityReturnsNull()
throws JspException {
authorizeTag.setIfAnyGranted("ROLE_TELLER");
context.setAuthentication(new TestingAuthenticationToken("abc", "123",
SecurityContext.setAuthentication(new TestingAuthenticationToken(
"abc", "123",
new GrantedAuthority[] {new CustomGrantedAuthority(null)}));
try {
@ -69,14 +68,11 @@ public class AuthorizeTagCustomGrantedAuthorityTests extends TestCase {
new GrantedAuthority[] {new CustomGrantedAuthority(
"ROLE_TELLER")});
context = new SecureContextImpl();
context.setAuthentication(currentUser);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
//~ Inner Classes ==========================================================

View File

@ -19,8 +19,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import org.springframework.mock.web.MockPageContext;
@ -37,7 +36,6 @@ public class AuthorizeTagExpressionLanguageTests extends TestCase {
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private MockPageContext pageContext;
private SecureContextImpl context;
private TestingAuthenticationToken currentUser;
//~ Methods ================================================================
@ -78,13 +76,10 @@ public class AuthorizeTagExpressionLanguageTests extends TestCase {
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"),});
context = new SecureContextImpl();
context.setAuthentication(currentUser);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -19,8 +19,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
@ -37,14 +36,13 @@ public class AuthorizeTagTests extends TestCase {
//~ Instance fields ========================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private SecureContextImpl context;
private TestingAuthenticationToken currentUser;
//~ Methods ================================================================
public void testAlwaysReturnsUnauthorizedIfNoUserFound()
throws JspException {
context.setAuthentication(null);
SecurityContext.setAuthentication(null);
authorizeTag.setIfAllGranted("ROLE_TELLER");
assertEquals("prevents request - no principal in Context",
@ -82,7 +80,7 @@ public class AuthorizeTagTests extends TestCase {
public void testPreventsBodyOutputIfNoSecureContext()
throws JspException {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
authorizeTag.setIfAnyGranted("ROLE_BANKER");
assertEquals("prevents output - no context defined", Tag.SKIP_BODY,
@ -117,13 +115,10 @@ public class AuthorizeTagTests extends TestCase {
"ROLE_SUPERVISOR"), new GrantedAuthorityImpl(
"ROLE_TELLER"),});
context = new SecureContextImpl();
context.setAuthentication(currentUser);
ContextHolder.setContext(context);
SecurityContext.setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -18,21 +18,23 @@ package net.sf.acegisecurity.ui;
import junit.framework.TestCase;
import net.sf.acegisecurity.AccountExpiredException;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.BadCredentialsException;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.MockAuthenticationManager;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.ui.rememberme.TokenBasedRememberMeServices;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@ -42,8 +44,6 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;
/**
@ -69,6 +69,17 @@ public class AbstractProcessingFilterTests extends TestCase {
junit.textui.TestRunner.run(AbstractProcessingFilterTests.class);
}
public void testDefaultProcessesFilterUrlWithPathParameter() {
MockHttpServletRequest request = createMockRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockAbstractProcessingFilter filter = new MockAbstractProcessingFilter();
filter.setFilterProcessesUrl("/j_acegi_security_check");
request.setRequestURI(
"/mycontext/j_acegi_security_check;jsessionid=I8MIONOSTHOR");
assertTrue(filter.requiresAuthentication(request, response));
}
public void testDoFilterWithNonHttpServletRequestDetected()
throws Exception {
AbstractProcessingFilter filter = new MockAbstractProcessingFilter();
@ -118,7 +129,7 @@ public class AbstractProcessingFilterTests extends TestCase {
chain);
assertEquals("/myApp/failed.jsp", response.getRedirectedUrl());
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
//Prepare again, this time using the exception mapping
filter = new MockAbstractProcessingFilter(new AccountExpiredException(
@ -136,7 +147,7 @@ public class AbstractProcessingFilterTests extends TestCase {
chain);
assertEquals("/myApp/accountExpired.jsp", response.getRedirectedUrl());
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testFilterProcessesUrlVariationsRespected()
@ -162,10 +173,9 @@ public class AbstractProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertEquals("/logged_in.jsp", response.getRedirectedUrl());
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
assertEquals("test",
SecureContextUtils.getSecureContext().getAuthentication()
.getPrincipal().toString());
SecurityContext.getAuthentication().getPrincipal().toString());
}
public void testGettersSetters() {
@ -237,20 +247,9 @@ public class AbstractProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertEquals("/logged_in.jsp", response.getRedirectedUrl());
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
assertEquals("test",
SecureContextUtils.getSecureContext().getAuthentication()
.getPrincipal().toString());
}
public void testDefaultProcessesFilterUrlWithPathParameter() {
MockHttpServletRequest request = createMockRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockAbstractProcessingFilter filter = new MockAbstractProcessingFilter();
filter.setFilterProcessesUrl("/j_acegi_security_check");
request.setRequestURI("/mycontext/j_acegi_security_check;jsessionid=I8MIONOSTHOR");
assertTrue(filter.requiresAuthentication(request, response));
SecurityContext.getAuthentication().getPrincipal().toString());
}
public void testStartupDetectsInvalidAuthenticationFailureUrl()
@ -339,10 +338,9 @@ public class AbstractProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertEquals("/logged_in.jsp", response.getRedirectedUrl());
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
assertEquals("test",
SecureContextUtils.getSecureContext().getAuthentication()
.getPrincipal().toString());
SecurityContext.getAuthentication().getPrincipal().toString());
// Now try again but this time have filter deny access
// Setup our HTTP request
@ -358,7 +356,7 @@ public class AbstractProcessingFilterTests extends TestCase {
// Test
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testSuccessfulAuthenticationButWithAlwaysUseDefaultTargetUrlCausesRedirectToDefaultTargetUrl()
@ -387,7 +385,7 @@ public class AbstractProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertEquals("/foobar", response.getRedirectedUrl());
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
}
public void testSuccessfulAuthenticationCausesRedirectToSessionSpecifiedUrl()
@ -412,25 +410,17 @@ public class AbstractProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertEquals("/my-destination", response.getRedirectedUrl());
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
}
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
Filter filter, ServletRequest request, ServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
SecurityContext.setAuthentication(null);
}
private MockHttpServletRequest createMockRequest() {
@ -444,6 +434,14 @@ public class AbstractProcessingFilterTests extends TestCase {
return request;
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
Filter filter, ServletRequest request, ServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
//~ Inner Classes ==========================================================
private class MockAbstractProcessingFilter extends AbstractProcessingFilter {
@ -462,10 +460,6 @@ public class AbstractProcessingFilterTests extends TestCase {
this.exceptionToThrow = exceptionToThrow;
}
public boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return super.requiresAuthentication(request, response);
}
private MockAbstractProcessingFilter() {
super();
}
@ -485,6 +479,11 @@ public class AbstractProcessingFilterTests extends TestCase {
}
public void init(FilterConfig arg0) throws ServletException {}
public boolean requiresAuthentication(HttpServletRequest request,
HttpServletResponse response) {
return super.requiresAuthentication(request, response);
}
}
private class MockFilterChain implements FilterChain {

View File

@ -21,16 +21,15 @@ import net.sf.acegisecurity.MockAuthenticationEntryPoint;
import net.sf.acegisecurity.MockAuthenticationManager;
import net.sf.acegisecurity.MockFilterConfig;
import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import org.apache.commons.codec.binary.Base64;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
@ -116,7 +115,7 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testGettersSetters() {
@ -134,7 +133,8 @@ public class BasicProcessingFilterTests extends TestCase {
// Setup our HTTP request
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -154,7 +154,7 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testNormalOperation() throws Exception {
@ -182,10 +182,9 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
assertEquals("marissa",
((UserDetails) SecureContextUtils.getSecureContext()
.getAuthentication().getPrincipal())
((UserDetails) SecurityContext.getAuthentication().getPrincipal())
.getUsername());
}
@ -213,7 +212,7 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testStartupDetectsMissingAuthenticationEntryPoint()
@ -269,10 +268,9 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
assertEquals("marissa",
((UserDetails) SecureContextUtils.getSecureContext()
.getAuthentication().getPrincipal())
((UserDetails) SecurityContext.getAuthentication().getPrincipal())
.getUsername());
// NOW PERFORM FAILED AUTHENTICATION
@ -291,7 +289,7 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -320,18 +318,18 @@ public class BasicProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,

View File

@ -20,9 +20,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.DisabledException;
import net.sf.acegisecurity.MockFilterConfig;
import net.sf.acegisecurity.UserDetails;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.dao.AuthenticationDao;
import net.sf.acegisecurity.providers.dao.UserCache;
import net.sf.acegisecurity.providers.dao.UsernameNotFoundException;
@ -32,12 +30,16 @@ import org.apache.commons.codec.binary.Base64;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.util.StringUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.Filter;
@ -117,7 +119,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -138,10 +141,11 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String header = response.getHeader("WWW-Authenticate").toString()
.substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries,
"=", "\"");
@ -171,7 +175,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testGettersSetters() {
@ -216,7 +220,7 @@ public class DigestProcessingFilterTests extends TestCase {
chain);
assertEquals(401, response.getStatus());
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testMalformedHeaderReturnsForbidden() throws Exception {
@ -242,7 +246,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -264,7 +268,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -284,7 +289,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -307,7 +312,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -327,7 +333,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -350,7 +356,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -370,7 +377,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -393,7 +400,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -413,7 +421,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -434,7 +442,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -454,10 +463,9 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
assertEquals("marissa",
((UserDetails) SecureContextUtils.getSecureContext()
.getAuthentication().getPrincipal())
((UserDetails) SecurityContext.getAuthentication().getPrincipal())
.getUsername());
}
@ -485,7 +493,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
}
public void testStartupDetectsMissingAuthenticationDao()
@ -532,7 +540,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -552,7 +561,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNotNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNotNull(SecurityContext.getAuthentication());
// Now retry, giving an invalid nonce
password = "WRONG_PASSWORD";
@ -561,12 +570,13 @@ public class DigestProcessingFilterTests extends TestCase {
request = new MockHttpServletRequest();
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
executeFilterInContainerSimulator(config, filter, request, response,
chain);
// Check we lost our previous authentication
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -588,7 +598,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -608,7 +619,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -629,7 +640,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -649,7 +661,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -670,7 +682,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -690,7 +703,7 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
@ -711,7 +724,8 @@ public class DigestProcessingFilterTests extends TestCase {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
request.addHeader("Authorization",
createAuthorizationHeader(username, realm, nonce, uri, responseDigest, qop, nc, cnonce));
createAuthorizationHeader(username, realm, nonce, uri,
responseDigest, qop, nc, cnonce));
request.setServletPath("/some_file.html");
// Launch an application context and access our bean
@ -731,18 +745,27 @@ public class DigestProcessingFilterTests extends TestCase {
executeFilterInContainerSimulator(config, filter, request, response,
chain);
assertNull(SecureContextUtils.getSecureContext().getAuthentication());
assertNull(SecurityContext.getAuthentication());
assertEquals(401, response.getStatus());
}
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
private String createAuthorizationHeader(String username, String realm,
String nonce, String uri, String responseDigest, String qop, String nc,
String cnonce) {
return "Digest username=\"" + username + "\", realm=\"" + realm
+ "\", nonce=\"" + nonce + "\", uri=\"" + uri + "\", response=\""
+ responseDigest + "\", qop=" + qop + ", nc=" + nc + ", cnonce=\""
+ cnonce + "\"";
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
@ -763,32 +786,20 @@ public class DigestProcessingFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
MockHttpServletResponse response = new MockHttpServletResponse();
ep.commence(request, response, new DisabledException("foobar"));
// Break up response header
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String header = response.getHeader("WWW-Authenticate").toString()
.substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries,
"=", "\"");
return headerMap;
}
private String createAuthorizationHeader(String username,
String realm,
String nonce,
String uri,
String responseDigest,
String qop,
String nc,
String cnonce) {
return "Digest username=\"" + username + "\", realm=\"" + realm
+ "\", nonce=\"" + nonce + "\", uri=\"" + uri + "\", response=\""
+ responseDigest + "\", qop=" + qop + ", nc=" + nc + ", cnonce=\""
+ cnonce + "\"";
}
//~ Inner Classes ==========================================================

View File

@ -15,6 +15,18 @@
package net.sf.acegisecurity.ui.rememberme;
import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.MockFilterConfig;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
@ -26,22 +38,6 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.MockFilterConfig;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests {@link RememberMeProcessingFilter}.
@ -65,48 +61,23 @@ public class RememberMeProcessingFilterTests extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(RememberMeProcessingFilterTests.class);
}
public void testDoFilterWithNonHttpServletRequestDetected()
throws Exception {
public void testDetectsRememberMeServicesProperty()
throws Exception {
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
try {
filter.doFilter(null, new MockHttpServletResponse(),
new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletRequest",
expected.getMessage());
}
}
public void testDoFilterWithNonHttpServletResponseDetected()
throws Exception {
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
try {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("dc");
filter.doFilter(request, null,
new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletResponse",
expected.getMessage());
}
}
public void testDetectsRememberMeServicesProperty() throws Exception {
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
// check default is NullRememberMeServices
assertEquals(NullRememberMeServices.class, filter.getRememberMeServices().getClass());
assertEquals(NullRememberMeServices.class,
filter.getRememberMeServices().getClass());
// check getter/setter
filter.setRememberMeServices(new TokenBasedRememberMeServices());
assertEquals(TokenBasedRememberMeServices.class, filter.getRememberMeServices().getClass());
assertEquals(TokenBasedRememberMeServices.class,
filter.getRememberMeServices().getClass());
// check detects if made null
filter.setRememberMeServices(null);
try {
filter.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@ -115,18 +86,45 @@ public class RememberMeProcessingFilterTests extends TestCase {
}
}
public void testDoFilterWithNonHttpServletRequestDetected()
throws Exception {
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
try {
filter.doFilter(null, new MockHttpServletResponse(),
new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletRequest",
expected.getMessage());
}
}
public void testDoFilterWithNonHttpServletResponseDetected()
throws Exception {
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
try {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("dc");
filter.doFilter(request, null, new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletResponse",
expected.getMessage());
}
}
public void testOperationWhenAuthenticationExistsInContextHolder()
throws Exception {
// Put an Authentication object into the ContextHolder
SecureContext sc = SecureContextUtils.getSecureContext();
Authentication originalAuth = new TestingAuthenticationToken("user",
"password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
sc.setAuthentication(originalAuth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(originalAuth);
// Setup our filter correctly
Authentication remembered = new TestingAuthenticationToken("remembered",
Authentication remembered = new TestingAuthenticationToken("remembered",
"password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_REMEMBERED")});
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
@ -137,17 +135,15 @@ public class RememberMeProcessingFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(),
new MockFilterChain(true));
request, new MockHttpServletResponse(), new MockFilterChain(true));
// Ensure filter didn't change our original object
assertEquals(originalAuth,
SecureContextUtils.getSecureContext().getAuthentication());
assertEquals(originalAuth, SecurityContext.getAuthentication());
}
public void testOperationWhenNoAuthenticationInContextHolder()
throws Exception {
Authentication remembered = new TestingAuthenticationToken("remembered",
Authentication remembered = new TestingAuthenticationToken("remembered",
"password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_REMEMBERED")});
RememberMeProcessingFilter filter = new RememberMeProcessingFilter();
@ -157,25 +153,22 @@ public class RememberMeProcessingFilterTests extends TestCase {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(new MockFilterConfig(), filter,
request, new MockHttpServletResponse(),
new MockFilterChain(true));
request, new MockHttpServletResponse(), new MockFilterChain(true));
Authentication auth = SecurityContext.getAuthentication();
Authentication auth = SecureContextUtils.getSecureContext()
.getAuthentication();
// Ensure filter setup with our remembered authentication object
assertEquals(remembered,
SecureContextUtils.getSecureContext().getAuthentication());
assertEquals(remembered, SecurityContext.getAuthentication());
}
protected void setUp() throws Exception {
super.setUp();
ContextHolder.setContext(new SecureContextImpl());
SecurityContext.setAuthentication(null);
}
protected void tearDown() throws Exception {
super.tearDown();
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
@ -208,25 +201,24 @@ public class RememberMeProcessingFilterTests extends TestCase {
}
}
}
private class MockRememberMeServices implements RememberMeServices
{
private Authentication authToReturn;
public MockRememberMeServices(Authentication authToReturn) {
this.authToReturn = authToReturn;
}
public Authentication autoLogin(HttpServletRequest request,
HttpServletResponse response) {
return authToReturn;
}
public void loginFail(HttpServletRequest request,
HttpServletResponse response) {
}
public void loginSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication successfulAuthentication) {
}
}
private class MockRememberMeServices implements RememberMeServices {
private Authentication authToReturn;
public MockRememberMeServices(Authentication authToReturn) {
this.authToReturn = authToReturn;
}
public Authentication autoLogin(HttpServletRequest request,
HttpServletResponse response) {
return authToReturn;
}
public void loginFail(HttpServletRequest request,
HttpServletResponse response) {}
public void loginSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication successfulAuthentication) {}
}
}

View File

@ -17,28 +17,24 @@ package net.sf.acegisecurity.ui.x509;
import junit.framework.TestCase;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.providers.x509.X509TestUtils;
import net.sf.acegisecurity.providers.x509.X509AuthenticationToken;
import net.sf.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.AuthenticationManager;
import net.sf.acegisecurity.BadCredentialsException;
import net.sf.acegisecurity.MockAuthenticationManager;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.x509.X509AuthenticationToken;
import net.sf.acegisecurity.providers.x509.X509TestUtils;
import net.sf.acegisecurity.ui.AbstractProcessingFilter;
import net.sf.acegisecurity.util.MockFilterChain;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.security.cert.X509Certificate;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import java.security.cert.X509Certificate;
/**
* Tests {@link net.sf.acegisecurity.ui.x509.X509ProcessingFilter}.
@ -64,18 +60,29 @@ public class X509ProcessingFilterTests extends TestCase {
}
public void tearDown() {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testNeedsAuthenticationManager() throws Exception {
public void testAuthenticationIsNullWithNoCertificate()
throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(true);
AuthenticationManager authMgr = new MockX509AuthenticationManager();
X509ProcessingFilter filter = new X509ProcessingFilter();
try {
filter.afterPropertiesSet();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException failed) {
// ignored
}
filter.setAuthenticationManager(authMgr);
SecurityContext.setAuthentication(null);
filter.doFilter(request, response, chain);
Object lastException = request.getSession().getAttribute(AbstractProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY);
assertNull("Authentication should be null",
SecurityContext.getAuthentication());
assertTrue("BadCredentialsException should have been thrown",
lastException instanceof BadCredentialsException);
}
public void testDoFilterWithNonHttpServletRequestDetected()
@ -106,6 +113,41 @@ public class X509ProcessingFilterTests extends TestCase {
}
}
public void testFailedAuthentication() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(true);
request.setAttribute("javax.servlet.request.X509Certificate",
new X509Certificate[] {X509TestUtils.buildTestCertificate()});
AuthenticationManager authMgr = new MockAuthenticationManager(false);
SecurityContext.setAuthentication(null);
X509ProcessingFilter filter = new X509ProcessingFilter();
filter.setAuthenticationManager(authMgr);
filter.afterPropertiesSet();
filter.init(null);
filter.doFilter(request, response, chain);
filter.destroy();
Authentication result = SecurityContext.getAuthentication();
assertNull(result);
}
public void testNeedsAuthenticationManager() throws Exception {
X509ProcessingFilter filter = new X509ProcessingFilter();
try {
filter.afterPropertiesSet();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException failed) {
// ignored
}
}
public void testNormalOperation() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
@ -113,15 +155,11 @@ public class X509ProcessingFilterTests extends TestCase {
FilterChain chain = new MockFilterChain(true);
request.setAttribute("javax.servlet.request.X509Certificate",
new X509Certificate[] {X509TestUtils.buildTestCertificate()});
new X509Certificate[] {X509TestUtils.buildTestCertificate()});
AuthenticationManager authMgr = new MockX509AuthenticationManager();
ContextHolder.setContext(new SecureContextImpl());
SecureContext ctx = SecureContextUtils.getSecureContext();
ctx.setAuthentication(null);
SecurityContext.setAuthentication(null);
X509ProcessingFilter filter = new X509ProcessingFilter();
@ -131,99 +169,27 @@ public class X509ProcessingFilterTests extends TestCase {
filter.doFilter(request, response, chain);
filter.destroy();
Authentication result = ctx.getAuthentication();
Authentication result = SecurityContext.getAuthentication();
assertNotNull(result);
}
public void testFailedAuthentication() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(true);
request.setAttribute("javax.servlet.request.X509Certificate",
new X509Certificate[] {X509TestUtils.buildTestCertificate()});
AuthenticationManager authMgr = new MockAuthenticationManager(false);
ContextHolder.setContext(new SecureContextImpl());
SecureContext ctx = SecureContextUtils.getSecureContext();
ctx.setAuthentication(null);
X509ProcessingFilter filter = new X509ProcessingFilter();
filter.setAuthenticationManager(authMgr);
filter.afterPropertiesSet();
filter.init(null);
filter.doFilter(request, response, chain);
filter.destroy();
Authentication result = ctx.getAuthentication();
assertNull(result);
}
public void testAuthenticationIsNullWithNoCertificate() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(true);
AuthenticationManager authMgr = new MockX509AuthenticationManager();
X509ProcessingFilter filter = new X509ProcessingFilter();
filter.setAuthenticationManager(authMgr);
ContextHolder.setContext(new SecureContextImpl());
filter.doFilter(request, response, chain);
SecureContext ctx = SecureContextUtils.getSecureContext();
Object lastException = request.getSession().getAttribute(
AbstractProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY);
assertNull("Authentication should be null", ctx.getAuthentication());
assertTrue("BadCredentialsException should have been thrown",
lastException instanceof BadCredentialsException);
}
public void testDoesNothingWithExistingSecurityContext() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain(true);
Authentication token = new AnonymousAuthenticationToken("dummy", "dummy",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
ContextHolder.setContext(new SecureContextImpl());
SecureContext ctx = SecureContextUtils.getSecureContext();
ctx.setAuthentication(token);
X509ProcessingFilter filter = new X509ProcessingFilter();
filter.doFilter(request, response, chain);
assertEquals("Existing token should be unchanged", token, ctx.getAuthentication());
}
//~ Inner Classes ==========================================================
private static class MockX509AuthenticationManager implements AuthenticationManager {
private static class MockX509AuthenticationManager
implements AuthenticationManager {
public Authentication authenticate(Authentication a) {
if(!(a instanceof X509AuthenticationToken)) {
TestCase.fail("Needed an X509Authentication token but found " + a);
if (!(a instanceof X509AuthenticationToken)) {
TestCase.fail("Needed an X509Authentication token but found "
+ a);
}
if(a.getCredentials() == null) {
throw new BadCredentialsException("Mock authentication manager rejecting null certificate");
if (a.getCredentials() == null) {
throw new BadCredentialsException(
"Mock authentication manager rejecting null certificate");
}
return a;
}
}
}

View File

@ -20,14 +20,11 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import net.sf.acegisecurity.providers.dao.User;
import net.sf.acegisecurity.wrapper.ContextHolderAwareRequestWrapper;
import org.springframework.mock.web.MockHttpServletRequest;
@ -60,15 +57,14 @@ public class ContextHolderAwareRequestWrapperTests extends TestCase {
public void testCorrectOperationWithStringBasedPrincipal()
throws Exception {
SecureContext sc = new SecureContextImpl();
Authentication auth = new TestingAuthenticationToken("marissa",
"koala",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FOO")});
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/");
ContextHolderAwareRequestWrapper wrapper = new ContextHolderAwareRequestWrapper(request);
assertEquals("marissa", wrapper.getRemoteUser());
@ -76,22 +72,21 @@ public class ContextHolderAwareRequestWrapperTests extends TestCase {
assertFalse(wrapper.isUserInRole("ROLE_NOT_GRANTED"));
assertEquals(auth, wrapper.getUserPrincipal());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testCorrectOperationWithUserDetailsBasedPrincipal()
throws Exception {
SecureContext sc = new SecureContextImpl();
Authentication auth = new TestingAuthenticationToken(new User(
"marissaAsUserDetails", "koala", true, true, true, true,
new GrantedAuthority[] {}), "koala",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_HELLO"), new GrantedAuthorityImpl(
"ROLE_FOOBAR")});
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/");
ContextHolderAwareRequestWrapper wrapper = new ContextHolderAwareRequestWrapper(request);
assertEquals("marissaAsUserDetails", wrapper.getRemoteUser());
@ -101,45 +96,32 @@ public class ContextHolderAwareRequestWrapperTests extends TestCase {
assertTrue(wrapper.isUserInRole("ROLE_HELLO"));
assertEquals(auth, wrapper.getUserPrincipal());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public void testNullAuthenticationHandling() throws Exception {
SecureContext sc = new SecureContextImpl();
sc.setAuthentication(null);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(null);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/");
ContextHolderAwareRequestWrapper wrapper = new ContextHolderAwareRequestWrapper(request);
assertNull(wrapper.getRemoteUser());
assertFalse(wrapper.isUserInRole("ROLE_ANY"));
assertNull(wrapper.getUserPrincipal());
ContextHolder.setContext(null);
}
public void testNullContextHolderHandling() throws Exception {
ContextHolder.setContext(null);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/");
ContextHolderAwareRequestWrapper wrapper = new ContextHolderAwareRequestWrapper(request);
assertNull(wrapper.getRemoteUser());
assertFalse(wrapper.isUserInRole("ROLE_ANY"));
assertNull(wrapper.getUserPrincipal());
SecurityContext.setAuthentication(null);
}
public void testNullPrincipalHandling() throws Exception {
SecureContext sc = new SecureContextImpl();
Authentication auth = new TestingAuthenticationToken(null, "koala",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_HELLO"), new GrantedAuthorityImpl(
"ROLE_FOOBAR")});
sc.setAuthentication(auth);
ContextHolder.setContext(sc);
SecurityContext.setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/");
ContextHolderAwareRequestWrapper wrapper = new ContextHolderAwareRequestWrapper(request);
assertNull(wrapper.getRemoteUser());
@ -147,6 +129,6 @@ public class ContextHolderAwareRequestWrapperTests extends TestCase {
assertFalse(wrapper.isUserInRole("ROLE_FOOBAR")); // principal is null, so reject
assertNull(wrapper.getUserPrincipal());
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -326,115 +326,67 @@
<sect1 id="security-request-contexts">
<title>Request Contexts</title>
<sect2 id="security-contexts">
<title>Contexts</title>
<sect2 id="security-contexts-history">
<title>Historical Approach</title>
<para>Many applications require a way of sharing objects between
classes, but without resorting to passing them in method signatures.
This is commonly achieved by using a <literal>ThreadLocal</literal>.
The Acegi Security System for Spring uses
<literal>ThreadLocal</literal> functionality and introduces the
concept of "request contexts".</para>
<para>By placing an object into a request context, that object becomes
available to any other object on the current thread of execution. The
request context is not passed around as a method parameter, but is
held in a <literal>ThreadLocal</literal>. The Acegi Security System
for Spring uses the request context to pass around the authentication
request and response.</para>
<para><mediaobject>
<imageobject role="html">
<imagedata align="center" fileref="images/Context.gif"
format="GIF" />
</imageobject>
<caption>
<para>Figure 2: The ContextHolder</para>
</caption>
</mediaobject></para>
<para>A request context is a concrete implementation of the
<literal>Context</literal> interface, which exposes a single
method:</para>
<programlisting>public void validate() throws ContextInvalidException;</programlisting>
<para>This <literal>validate()</literal> method is called to confirm
the <literal>Context</literal> is properly setup. An implementation
will typically use this method to check that the objects it holds are
properly setup.</para>
<para>The <literal>ContextHolder</literal> class makes the
<literal>Context</literal> available to the current thread of
execution using a <literal>ThreadLocal</literal>. A
<literal>ContextInterceptor</literal> is also provided, which is
intended to be chained into the bean context using
<literal>ProxyFactoryBean</literal>. The
<literal>ContextInterceptor</literal> simply calls
<literal>Context.validate()</literal>, which guarantees to business
methods that a valid <literal>Context</literal> is available from the
<literal>ContextHolder</literal>.</para>
<para>Prior to release 0.9.0, Acegi Security used a
<literal>ContextHolder</literal> to store a <literal>Context</literal>
between sessions. A particular subclass of <literal>Context</literal>,
<literal>SecureContext</literal> defined an interface used for storage
of the <literal>Authentication</literal> object. The
<literal>ContextHolder</literal> was a <literal>ThreadLocal</literal>.
This was removed from 0.9.0 after discussion with other Spring
developers for the sake of consistency. See for example
<literal>http://article.gmane.org/gmane.comp.java.springframework.devel/8290</literal>.
This history is mentioned as the long period
<literal>ContextHolder</literal> was used will likely mean that
certain documentation you encounter concerning Acegi Security might
still refer to <literal>ContextHolder</literal>. Generally you can
just substitute "<literal>SecurityContext</literal>" for
"<literal>ContextHolder</literal>" and you'll have the primary meaning
of such documentation.</para>
</sect2>
<sect2 id="security-contexts-secure-contexts">
<title>Secure Contexts</title>
<sect2 id="security-contexts-security-context">
<title>SecurityContext</title>
<para>The Acegi Security System for Spring requires the
<literal>ContextHolder</literal> to contain a request context that
implements the <literal>SecureContext</literal> interface. An
implementation is provided named <literal>SecureContextImpl</literal>.
The <literal>SecureContext</literal> simply extends the
<literal>Context</literal> discussed above and adds a holder and
validation for an <literal>Authentication</literal> object.</para>
</sect2>
<sect2 id="security-contexts-custom-contexts">
<title>Custom Contexts</title>
<para>Developers can create their own request context classes to store
application-specific objects. Such request context classes will need
to implement the <literal>Context</literal> interface. If the Acegi
Security System for Spring is to be used, developers must ensure any
custom request contexts implement the <literal>SecureContext</literal>
interface.</para>
<para>The Acegi Security System for Spring uses a
<literal>SecurityContext</literal> to store the
<literal>Authentication</literal>. All Acegi Security classes query
the <literal>SecurityContext</literal> for obtaining the currently
principal. <literal>SecurityContext</literal> is an
<literal>InheritableThreadLocal</literal>, meaning it is associated
with the current thread of execution.
<literal>SecurityContext</literal> simply provides a single getter and
setter pair for the <literal>Authentication</literal> object.</para>
</sect2>
<sect2 id="security-contexts-storage">
<title>Context Storage</title>
<para>Central to Acegi Security's design is that the contents of the
<literal>ContextHolder</literal> (ie the <literal>Context</literal>)
can be stored between web requests. This is so that a successfully
authenticated principal can be identified on subsequent requests
through the <literal>Authentication</literal> stored inside a
<literal>SecureContext</literal> implementation. The
<literal>SecurityContext</literal> (which is simply an
<literal>Authentication</literal> object) can be stored between web
requests. This is so that a successfully authenticated principal can
be identified on subsequent requests through the
<literal>Authentication</literal> stored inside a
<literal>SecurityContext</literal>. The
<literal>HttpSessionContextIntegrationFilter</literal> exists to
automatically copy the contents of a well-defined
<literal>HttpSession</literal> attribute into the
<literal>ContextHolder</literal>, then at the end of each request,
copy the <literal>ContextHolder</literal> contents back into the
<literal>SecurityContext</literal>, then at the end of each request,
copy the <literal>SecurityContext</literal> contents back into the
<literal>HttpSession</literal> ready for next request.</para>
<para>It is essential - and an extremely common error of end users -
that <literal>HttpSessionContextIntegrationFilter</literal> appears
before any other Acegi Security filter. This is because other Acegi
Security filters (along with all Acegi Security classes) expect the
<literal>ContextHolder</literal> to contain a valid
<literal>SecureContext</literal> by the time they are called. Acegi
Security filters also expect to be able to modify the
<literal>ContextHolder</literal> contents as they see fit, and
something else will store those between requests if necessary. This is
why <literal>HttpSessionContextIntegrationFilter</literal> must be the
before any other Acegi Security filter. Acegi Security filters expect
to be able to modify the <literal>SecurityContext</literal> contents
as they see fit, and something else (namely
<literal>HttpSessionContextIntegrationFilter</literal>) will store
those between requests if necessary. This is why
<literal>HttpSessionContextIntegrationFilter</literal> must be the
first filter used.</para>
<para>The <literal>HttpSessionContextIntegrationFilter</literal> has
been designed to store all types of <literal>Context</literal> objects
- not merely Acegi Security related contexts. This means, for example,
that you can extend <literal>SecureContextImpl</literal> to store a
locale or some other parameter, and
<literal>HttpSessionContextIntegrationFilter</literal> will
automatically manage it between web requests.</para>
</sect2>
</sect1>

View File

@ -26,6 +26,7 @@
</properties>
<body>
<release version="0.9.0" date="In CVS">
<action dev="benalex" type="update">ContextHolder and related classes removed and replaced with SecurityContext</action>
<action dev="luke_t" type="update">Changed order of credentials verification and expiry checking in DaoAuthenticationProvider. Password must now be successfully verified before expired credentials are reported. </action>
<action dev="benalex" type="update">AnonymousProcessingFilter offers protected method to control when it should execute</action>
<action dev="benalex" type="fix">AbstractAuthenticationToken.getName() now returns username alone if UserDetails present</action>

View File

@ -0,0 +1,46 @@
<html>
<head>
<title>Acegi Security - Upgrading from version 0.8.0 to 1.0.0</title>
</head>
<body>
<h1>Upgrading from 0.8.0 to 1.0.0</h1>
<p>
The following should help most casual users of the project update their
applications:
<ul>
<li>The most significant change in 0.9.0 is that <code>ContextHolder</code> and all of its
related classes have been removed. This significant change was made for the sake of consistency
with the core Spring project's approach of a single <code>ThreadLocal</code> per use case,
instead of a shared <code>ThreadLocal</code> for multiple use cases as the previous
<code>ContextHolder</code> allowed. <b>This is an important change in 0.9.0.</b> Many applications
will need to modify their code (and possibly web views) if they directly interact with the old
<code>ContextHolder</code>. The replacement security <code>ThreadLocal</code> is called
<a href="../multiproject/acegi-security/xref/net/sf/acegisecurity/context/SecurityContext.html">
SecurityContext</a> and provides a single getter/setter for <code>Authentication</code>. There is
thus no need to work with <code>SecureContext</code> or <code>Context</code> anymore. <BR><BR>
To migrate, simply modify all your code that previously worked with <code>ContextHolder</code>,
<code>SecureContext</code> and <code>Context</code> to directly call <code>SecurityContext</code>.
You will also note that the <code>HttpSessionContextIntegrationFilter</code> no longer provides
a <code>context</code> property, so remove it from your application context XML. For the relatively
small number of users who had customised their context, you will need to write your own
<code>ThreadLocal</code> to provide functionality for your specific use case.<BR><BR>
We apologise for the inconvenience, but on a more positive note this means you receive strict
type checking, you no longer need to mess around with casting to and from <code>Context</code>
implementations, your applications no longer need to perform checking of <code>null</code> and
unexpected <code>Context</code> implementation types, and the new <code>SecurityContext</code>
is an <code>InheritableThreadLocal</code> - which should make life easier in rich client
environments.<br><br></li>
<li>AbstractProcessingFilter has changed its getter/setter approach used for customised
authentication exception directions. See the <a href="../multiproject/acegi-security/xref/net/sf/acegisecurity/ui/AbstractProcessingFilter.html">
AbstractProcessingFilter JavaDocs</a> to learn more.<br><br></li>
</ul>
</body>
</html>

View File

@ -1,21 +0,0 @@
<html>
<head>
<title>Acegi Security - Upgrading from version 0.8.0 to 1.0.0</title>
</head>
<body>
<h1>Upgrading from 0.8.0 to 1.0.0</h1>
<p>
The following should help most casual users of the project update their
applications:
<ul>
<li>AbstractProcessingFilter has changed its getter/setter approach used for customised
authentication exception directions. See the <a href="../multiproject/acegi-security/xref/net/sf/acegisecurity/ui/AbstractProcessingFilter.html">
AbstractProcessingFilter JavaDocs</a> to learn more.<br><br></li>
</ul>
</body>
</html>

View File

@ -18,8 +18,7 @@ package sample.attributes;
import net.sf.acegisecurity.AccessDeniedException;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@ -67,12 +66,10 @@ public class Main {
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"), new GrantedAuthorityImpl(
"ROLE_PERMISSION_LIST")});
SecureContextImpl secureContext = new SecureContextImpl();
secureContext.setAuthentication(auth);
ContextHolder.setContext(secureContext);
SecurityContext.setAuthentication(auth);
}
private static void destroySecureContext() {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -20,8 +20,7 @@ import junit.framework.TestCase;
import net.sf.acegisecurity.AccessDeniedException;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.TestingAuthenticationToken;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@ -86,12 +85,10 @@ public class BankTests extends TestCase {
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"), new GrantedAuthorityImpl(
"ROLE_PERMISSION_LIST")});
SecureContextImpl secureContext = new SecureContextImpl();
secureContext.setAuthentication(auth);
ContextHolder.setContext(secureContext);
SecurityContext.setAuthentication(auth);
}
private static void destroySecureContext() {
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
}

View File

@ -16,9 +16,7 @@
package sample.contact;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.ContextHolder;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextImpl;
import net.sf.acegisecurity.context.SecurityContext;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.springframework.beans.factory.ListableBeanFactory;
@ -64,9 +62,7 @@ public class ClientApplication {
Map contactServices = this.beanFactory.getBeansOfType(ContactManager.class,
true, true);
SecureContext secureContext = new SecureContextImpl();
secureContext.setAuthentication(authentication);
ContextHolder.setContext(secureContext);
SecurityContext.setAuthentication(authentication);
for (Iterator it = contactServices.keySet().iterator(); it.hasNext();) {
String beanName = (String) it.next();
@ -140,7 +136,7 @@ public class ClientApplication {
System.out.println(stopWatch.prettyPrint());
}
ContextHolder.setContext(null);
SecurityContext.setAuthentication(null);
}
public static void main(String[] args) {

View File

@ -21,11 +21,12 @@ import net.sf.acegisecurity.acl.basic.AclObjectIdentity;
import net.sf.acegisecurity.acl.basic.BasicAclExtendedDao;
import net.sf.acegisecurity.acl.basic.NamedEntityObjectIdentity;
import net.sf.acegisecurity.acl.basic.SimpleAclEntry;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import net.sf.acegisecurity.context.SecurityContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.util.Assert;
import java.util.List;
@ -172,8 +173,7 @@ public class ContactManagerBackend extends ApplicationObjectSupport
}
protected String getUsername() {
Authentication auth = SecureContextUtils.getSecureContext()
.getAuthentication();
Authentication auth = SecurityContext.getAuthentication();
if (auth.getPrincipal() instanceof UserDetails) {
return ((UserDetails) auth.getPrincipal()).getUsername();

View File

@ -47,7 +47,6 @@
<bean id="httpRequestIntegrationFilter" class="net.sf.acegisecurity.adapters.HttpRequestIntegrationFilter"/>
<bean id="httpSessionContextIntegrationFilter" class="net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter">
<property name="context"><value>net.sf.acegisecurity.context.security.SecureContextImpl</value></property>
</bean>
<!-- ===================== HTTP CHANNEL REQUIREMENTS ==================== -->

View File

@ -48,7 +48,6 @@
</bean>
<bean id="httpSessionContextIntegrationFilter" class="net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter">
<property name="context"><value>net.sf.acegisecurity.context.security.SecureContextImpl</value></property>
</bean>
<bean id="casAuthenticationProvider" class="net.sf.acegisecurity.providers.cas.CasAuthenticationProvider">

View File

@ -1,19 +1,10 @@
<%@ page import="net.sf.acegisecurity.context.Context" %>
<%@ page import="net.sf.acegisecurity.context.ContextHolder" %>
<%@ page import="net.sf.acegisecurity.context.security.SecureContext" %>
<%@ page import="net.sf.acegisecurity.context.SecurityContext" %>
<%@ page import="net.sf.acegisecurity.Authentication" %>
<%@ page import="net.sf.acegisecurity.GrantedAuthority" %>
<%@ page import="net.sf.acegisecurity.adapters.AuthByAdapter" %>
<% Context context = ContextHolder.getContext();
if (context != null) { %>
Context on ContextHolder is of type: <%= context.getClass().getName() %><BR><BR>
<% if (context instanceof SecureContext) { %>
The Context implements SecureContext.<BR><BR>
<% SecureContext sc = (SecureContext) context;
Authentication auth = sc.getAuthentication();
<%
Authentication auth = SecurityContext.getAuthentication();
if (auth != null) { %>
Authentication object is of type: <%= auth.getClass().getName() %><BR><BR>
Authentication object as a String: <%= auth.toString() %><BR><BR>
@ -34,13 +25,4 @@ if (context != null) { %>
Authentication object is null.<BR>
This is an error and your Acegi Security application will not operate properly until corrected.<BR><BR>
<% }
} else { %>
<B>ContextHolder does not contain a SecureContext.</B><BR>
This is an error and your Acegi Security application will not operate properly until corrected.<BR><BR>
<% }
} else { %>
<B>ContextHolder on ContextHolder is null.</B><BR>
This indicates improper setup of the Acegi Security application. Refer to the reference documentation.<BR>
<%}
%>

View File

@ -87,7 +87,6 @@
</bean>
<bean id="httpSessionContextIntegrationFilter" class="net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter">
<property name="context"><value>net.sf.acegisecurity.context.security.SecureContextImpl</value></property>
</bean>
<bean id="rememberMeProcessingFilter" class="net.sf.acegisecurity.ui.rememberme.RememberMeProcessingFilter">

View File

@ -48,7 +48,6 @@
</bean>
<bean id="httpSessionContextIntegrationFilter" class="net.sf.acegisecurity.context.HttpSessionContextIntegrationFilter">
<property name="context"><value>net.sf.acegisecurity.context.security.SecureContextImpl</value></property>
</bean>
<bean id="x509AuthenticationProvider" class="net.sf.acegisecurity.providers.x509.X509AuthenticationProvider">