1
0
mirror of synced 2026-08-04 17:27:13 +00:00

Tidying up, removing compiler warnings etc.

This commit is contained in:
Luke Taylor
2008-12-20 00:16:49 +00:00
parent 8154161ef5
commit cc5966bc7e
255 changed files with 3993 additions and 4444 deletions
@@ -26,13 +26,10 @@ import org.springframework.security.userdetails.UserDetails;
* A <code>GrantedAuthority</code> must either represent itself as a
* <code>String</code> or be specifically supported by an {@link
* AccessDecisionManager}.
* </p>
*
* <p>
* Implementations must implement {@link Comparable} in order to ensure that
* array sorting logic guaranteed by {@link UserDetails#getAuthorities()} can
* be reliably implemented.
* </p>
*
* @author Ben Alex
* @version $Id$
@@ -73,16 +73,16 @@ public class GrantedAuthorityImpl implements GrantedAuthority, Serializable {
return this.role;
}
public int compareTo(Object o) {
if (o != null && o instanceof GrantedAuthority) {
String rhsRole = ((GrantedAuthority) o).getAuthority();
if (rhsRole == null) {
return -1;
}
return role.compareTo(rhsRole);
}
return -1;
}
public int compareTo(Object o) {
if (o != null && o instanceof GrantedAuthority) {
String rhsRole = ((GrantedAuthority) o).getAuthority();
if (rhsRole == null) {
return -1;
}
return role.compareTo(rhsRole);
}
return -1;
}
}
@@ -159,7 +159,7 @@ public class ConcurrentSessionControllerImpl implements ConcurrentSessionControl
this.sessionRegistry = sessionRegistry;
}
public SessionRegistry getSessionRegistry() {
return sessionRegistry;
}
public SessionRegistry getSessionRegistry() {
return sessionRegistry;
}
}
@@ -24,7 +24,6 @@ import org.springframework.security.ui.logout.SecurityContextLogoutHandler;
import org.springframework.security.util.UrlUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
@@ -17,45 +17,45 @@ import org.w3c.dom.Element;
* @version $Id$
*/
public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements BeanDefinitionParser {
private static final String CACHE_REF = "cache-ref";
public static final String CACHING_SUFFIX = ".caching";
/** UserDetailsService bean Id. For use in a stateful context (i.e. in AuthenticationProviderBDP) */
private String id;
protected abstract String getBeanClassName(Element element);
protected abstract void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder);
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClassName(element));
doParse(element, parserContext, builder);
RootBeanDefinition userService = (RootBeanDefinition) builder.getBeanDefinition();
String beanId = resolveId(element, userService, parserContext);
parserContext.getRegistry().registerBeanDefinition(beanId, userService);
String cacheRef = element.getAttribute(CACHE_REF);
// Register a caching version of the user service if there's a cache-ref
if (StringUtils.hasText(cacheRef)) {
BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder.rootBeanDefinition(CachingUserDetailsService.class);
cachingUSBuilder.addConstructorArgReference(beanId);
cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition();
parserContext.getRegistry().registerBeanDefinition(beanId + CACHING_SUFFIX, cachingUserService);
}
private static final String CACHE_REF = "cache-ref";
public static final String CACHING_SUFFIX = ".caching";
/** UserDetailsService bean Id. For use in a stateful context (i.e. in AuthenticationProviderBDP) */
private String id;
protected abstract String getBeanClassName(Element element);
protected abstract void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder);
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClassName(element));
doParse(element, parserContext, builder);
RootBeanDefinition userService = (RootBeanDefinition) builder.getBeanDefinition();
String beanId = resolveId(element, userService, parserContext);
parserContext.getRegistry().registerBeanDefinition(beanId, userService);
String cacheRef = element.getAttribute(CACHE_REF);
// Register a caching version of the user service if there's a cache-ref
if (StringUtils.hasText(cacheRef)) {
BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder.rootBeanDefinition(CachingUserDetailsService.class);
cachingUSBuilder.addConstructorArgReference(beanId);
cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition();
parserContext.getRegistry().registerBeanDefinition(beanId + CACHING_SUFFIX, cachingUserService);
}
id = beanId;
return null;
}
id = beanId;
return null;
}
private String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
throws BeanDefinitionStoreException {
String id = element.getAttribute("id");
@@ -76,7 +76,7 @@ public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements
return BeanIds.USER_DETAILS_SERVICE;
}
String getId() {
return id;
}
String getId() {
return id;
}
}
@@ -19,11 +19,11 @@ import org.w3c.dom.Element;
*/
public class AuthenticationManagerBeanDefinitionParser implements BeanDefinitionParser {
private static final String ATT_SESSION_CONTROLLER_REF = "session-controller-ref";
private static final String ATT_ALIAS = "alias";
private static final String ATT_ALIAS = "alias";
public BeanDefinition parse(Element element, ParserContext parserContext) {
ConfigUtils.registerProviderManagerIfNecessary(parserContext);
ConfigUtils.registerProviderManagerIfNecessary(parserContext);
String alias = element.getAttribute(ATT_ALIAS);
if (!StringUtils.hasText(alias)) {
@@ -33,16 +33,16 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
String sessionControllerRef = element.getAttribute(ATT_SESSION_CONTROLLER_REF);
if (StringUtils.hasText(sessionControllerRef)) {
BeanDefinition authManager = parserContext.getRegistry().getBeanDefinition(BeanIds.AUTHENTICATION_MANAGER);
BeanDefinition authManager = parserContext.getRegistry().getBeanDefinition(BeanIds.AUTHENTICATION_MANAGER);
ConfigUtils.setSessionControllerOnAuthenticationManager(parserContext,
BeanIds.CONCURRENT_SESSION_CONTROLLER, element);
authManager.getPropertyValues().addPropertyValue("sessionController",
new RuntimeBeanReference(sessionControllerRef));
BeanIds.CONCURRENT_SESSION_CONTROLLER, element);
authManager.getPropertyValues().addPropertyValue("sessionController",
new RuntimeBeanReference(sessionControllerRef));
RootBeanDefinition sessionRegistryInjector = new RootBeanDefinition(SessionRegistryInjectionBeanPostProcessor.class);
sessionRegistryInjector.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
sessionRegistryInjector.getConstructorArgumentValues().addGenericArgumentValue(sessionControllerRef);
parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_REGISTRY_INJECTION_POST_PROCESSOR, sessionRegistryInjector);
parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_REGISTRY_INJECTION_POST_PROCESSOR, sessionRegistryInjector);
}
parserContext.getRegistry().registerAlias(BeanIds.AUTHENTICATION_MANAGER, alias);
@@ -20,30 +20,30 @@ import org.w3c.dom.Element;
* @version $Id$
*/
public class BasicAuthenticationBeanDefinitionParser implements BeanDefinitionParser {
private String realmName;
private String realmName;
public BasicAuthenticationBeanDefinitionParser(String realmName) {
this.realmName = realmName;
}
public BasicAuthenticationBeanDefinitionParser(String realmName) {
this.realmName = realmName;
}
public BeanDefinition parse(Element elt, ParserContext parserContext) {
public BeanDefinition parse(Element elt, ParserContext parserContext) {
BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder.rootBeanDefinition(BasicProcessingFilter.class);
RootBeanDefinition entryPoint = new RootBeanDefinition(BasicProcessingFilterEntryPoint.class);
entryPoint.setSource(parserContext.extractSource(elt));
entryPoint.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
entryPoint.getPropertyValues().addPropertyValue("realmName", realmName);
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, entryPoint);
RootBeanDefinition entryPoint = new RootBeanDefinition(BasicProcessingFilterEntryPoint.class);
entryPoint.setSource(parserContext.extractSource(elt));
entryPoint.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
entryPoint.getPropertyValues().addPropertyValue("realmName", realmName);
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, entryPoint);
filterBuilder.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
filterBuilder.addPropertyValue("authenticationEntryPoint", new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT));
filterBuilder.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
filterBuilder.addPropertyValue("authenticationEntryPoint", new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT));
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_FILTER,
filterBuilder.getBeanDefinition());
ConfigUtils.addHttpFilter(parserContext, new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_FILTER));
parserContext.registerComponent(new BeanComponentDefinition(filterBuilder.getBeanDefinition(),
BeanIds.BASIC_AUTHENTICATION_FILTER));
return null;
}
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_FILTER,
filterBuilder.getBeanDefinition());
ConfigUtils.addHttpFilter(parserContext, new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_FILTER));
parserContext.registerComponent(new BeanComponentDefinition(filterBuilder.getBeanDefinition(),
BeanIds.BASIC_AUTHENTICATION_FILTER));
return null;
}
}
@@ -12,33 +12,33 @@ import org.springframework.util.Assert;
* @since 2.0
*/
class CachingUserDetailsService implements UserDetailsService {
private UserCache userCache = new NullUserCache();
private UserDetailsService delegate;
private UserCache userCache = new NullUserCache();
private UserDetailsService delegate;
CachingUserDetailsService(UserDetailsService delegate) {
this.delegate = delegate;
}
CachingUserDetailsService(UserDetailsService delegate) {
this.delegate = delegate;
}
public UserCache getUserCache() {
return userCache;
}
public UserCache getUserCache() {
return userCache;
}
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
public UserDetails loadUserByUsername(String username) {
UserDetails user = userCache.getUserFromCache(username);
if (user == null) {
user = delegate.loadUserByUsername(username);
}
Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " +
"This is an interface contract violation");
userCache.putUserInCache(user);
return user;
}
public UserDetails loadUserByUsername(String username) {
UserDetails user = userCache.getUserFromCache(username);
if (user == null) {
user = delegate.loadUserByUsername(username);
}
Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " +
"This is an interface contract violation");
userCache.putUserInCache(user);
return user;
}
}
@@ -87,11 +87,13 @@ abstract class ConfigUtils {
((ArrayList) authManager.getPropertyValues().getPropertyValue("providerBeanNames").getValue()).add(beanName);
}
@SuppressWarnings("unchecked")
static ManagedList getRegisteredAfterInvocationProviders(ParserContext parserContext) {
BeanDefinition manager = registerAfterInvocationProviderManagerIfNecessary(parserContext);
return (ManagedList) manager.getPropertyValues().getPropertyValue("providers").getValue();
}
@SuppressWarnings("unchecked")
private static BeanDefinition registerAfterInvocationProviderManagerIfNecessary(ParserContext parserContext) {
if(parserContext.getRegistry().containsBeanDefinition(BeanIds.AFTER_INVOCATION_MANAGER)) {
return parserContext.getRegistry().getBeanDefinition(BeanIds.AFTER_INVOCATION_MANAGER);
@@ -27,7 +27,6 @@ public class FilterInvocationDefinitionSourceBeanDefinitionParser extends Abstra
return "org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource";
}
@SuppressWarnings("unchecked")
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
List<Element> interceptUrls = DomUtils.getChildElementsByTagName(element, "intercept-url");
@@ -166,6 +166,7 @@ class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionParser {
pc.getRegistry().registerBeanDefinition(ACCESS_MANAGER_ID, accessMgrBuilder.getBeanDefinition());
}
@SuppressWarnings("unchecked")
private void registerDelegatingMethodDefinitionSource(ParserContext parserContext, ManagedList delegates, Object source) {
if (parserContext.getRegistry().containsBeanDefinition(DELEGATING_METHOD_DEFINITION_SOURCE_ID)) {
parserContext.getReaderContext().error("Duplicate <global-method-security> detected.", source);
@@ -42,7 +42,6 @@ class InternalInterceptMethodsBeanDefinitionDecorator extends AbstractIntercepto
static final String ATT_ACCESS = "access";
private static final String ATT_ACCESS_MGR = "access-decision-manager-ref";
@SuppressWarnings("unchecked")
protected BeanDefinition createInterceptorDefinition(Node node) {
Element interceptMethodsElt = (Element)node;
BeanDefinitionBuilder interceptor = BeanDefinitionBuilder.rootBeanDefinition(MethodSecurityInterceptor.class);
@@ -11,11 +11,11 @@ import org.w3c.dom.Element;
* @version $Id$
*/
public class JdbcUserServiceBeanDefinitionParser extends AbstractUserDetailsServiceBeanDefinitionParser {
static final String ATT_DATA_SOURCE = "data-source-ref";
static final String ATT_USERS_BY_USERNAME_QUERY = "users-by-username-query";
static final String ATT_AUTHORITIES_BY_USERNAME_QUERY = "authorities-by-username-query";
static final String ATT_GROUP_AUTHORITIES_QUERY = "group-authorities-by-username-query";
static final String ATT_ROLE_PREFIX = "role-prefix";
static final String ATT_DATA_SOURCE = "data-source-ref";
static final String ATT_USERS_BY_USERNAME_QUERY = "users-by-username-query";
static final String ATT_AUTHORITIES_BY_USERNAME_QUERY = "authorities-by-username-query";
static final String ATT_GROUP_AUTHORITIES_QUERY = "group-authorities-by-username-query";
static final String ATT_ROLE_PREFIX = "role-prefix";
protected String getBeanClassName(Element element) {
return "org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager";
@@ -14,8 +14,8 @@ public class SecurityNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
// Parsers
registerBeanDefinitionParser(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser());
registerBeanDefinitionParser(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser());
registerBeanDefinitionParser(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser());
registerBeanDefinitionParser(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser());
registerBeanDefinitionParser(Elements.LDAP_USER_SERVICE, new LdapUserServiceBeanDefinitionParser());
registerBeanDefinitionParser(Elements.HTTP, new HttpSecurityBeanDefinitionParser());
registerBeanDefinitionParser(Elements.USER_SERVICE, new UserServiceBeanDefinitionParser());
@@ -56,7 +56,6 @@ class SessionRegistryInjectionBeanPostProcessor implements BeanPostProcessor, Be
return bean;
}
@SuppressWarnings("unchecked")
private SessionRegistry getSessionRegistry() {
if (sessionRegistry != null) {
return sessionRegistry;
@@ -84,7 +83,7 @@ class SessionRegistryInjectionBeanPostProcessor implements BeanPostProcessor, Be
logger.warn("More than one SessionRegistry instance in application context. Possible configuration errors may result.");
}
sessionRegistry = (SessionRegistry) sessionRegs.get(0);
sessionRegistry = sessionRegs.get(0);
return sessionRegistry;
}
@@ -30,11 +30,11 @@ import org.springframework.util.Assert;
public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticationEvent {
//~ Instance fields ================================================================================================
private Class generatedBy;
private Class<?> generatedBy;
//~ Constructors ===================================================================================================
public InteractiveAuthenticationSuccessEvent(Authentication authentication, Class generatedBy) {
public InteractiveAuthenticationSuccessEvent(Authentication authentication, Class<?> generatedBy) {
super(authentication);
Assert.notNull(generatedBy);
this.generatedBy = generatedBy;
@@ -48,7 +48,7 @@ public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticatio
*
* @return the class
*/
public Class getGeneratedBy() {
public Class<?> getGeneratedBy() {
return generatedBy;
}
}
@@ -23,8 +23,9 @@ import org.springframework.util.ClassUtils;
/**
* Outputs authentication-related application events to Commons Logging.<P>All authentication events are logged at
* the warning level.</p>
* Outputs authentication-related application events to Commons Logging.
* <p>
* All authentication events are logged at the warning level.
*
* @author Ben Alex
* @version $Id$
@@ -44,7 +45,7 @@ public class LoggerListener implements ApplicationListener {
AbstractAuthenticationEvent authEvent = (AbstractAuthenticationEvent) event;
if (!logInteractiveAuthenticationSuccessEvents && authEvent instanceof InteractiveAuthenticationSuccessEvent) {
return;
return;
}
if (logger.isWarnEnabled()) {
@@ -62,12 +63,12 @@ public class LoggerListener implements ApplicationListener {
}
}
public boolean isLogInteractiveAuthenticationSuccessEvents() {
return logInteractiveAuthenticationSuccessEvents;
}
public boolean isLogInteractiveAuthenticationSuccessEvents() {
return logInteractiveAuthenticationSuccessEvents;
}
public void setLogInteractiveAuthenticationSuccessEvents(
boolean logInteractiveAuthenticationSuccessEvents) {
this.logInteractiveAuthenticationSuccessEvents = logInteractiveAuthenticationSuccessEvents;
}
public void setLogInteractiveAuthenticationSuccessEvents(
boolean logInteractiveAuthenticationSuccessEvents) {
this.logInteractiveAuthenticationSuccessEvents = logInteractiveAuthenticationSuccessEvents;
}
}
@@ -20,7 +20,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -88,7 +87,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
return findAttributesSpecifiedAgainst(method, targetClass);
}
private List<ConfigAttribute> findAttributesSpecifiedAgainst(Method method, Class clazz) {
private List<ConfigAttribute> findAttributesSpecifiedAgainst(Method method, Class<?> clazz) {
RegisteredMethod registeredMethod = new RegisteredMethod(method, clazz);
if (methodMap.containsKey(registeredMethod)) {
return (List<ConfigAttribute>) methodMap.get(registeredMethod);
@@ -118,7 +117,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
Assert.hasText(methodName, "Method not found for '" + name + "'");
String typeName = name.substring(0, lastDotIndex);
Class type = ClassUtils.resolveClassName(typeName, this.beanClassLoader);
Class<?> type = ClassUtils.resolveClassName(typeName, this.beanClassLoader);
addSecureMethod(type, methodName, attr);
}
@@ -131,7 +130,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
* @param mappedName mapped method name, which the javaType has declared or inherited
* @param attr required authorities associated with the method
*/
public void addSecureMethod(Class javaType, String mappedName, List<ConfigAttribute> attr) {
public void addSecureMethod(Class<?> javaType, String mappedName, List<ConfigAttribute> attr) {
String name = javaType.getName() + '.' + mappedName;
if (logger.isDebugEnabled()) {
@@ -179,7 +178,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
* the existing match will be retained, so that if this method is called for a more general pointcut
* it will not override a more specific one which has already been added. This
*/
public void addSecureMethod(Class javaType, Method method, List<ConfigAttribute> attr) {
public void addSecureMethod(Class<?> javaType, Method method, List<ConfigAttribute> attr) {
RegisteredMethod key = new RegisteredMethod(method, javaType);
if (methodMap.containsKey(key)) {
@@ -255,9 +254,9 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
*/
private class RegisteredMethod {
private Method method;
private Class registeredJavaType;
private Class<?> registeredJavaType;
public RegisteredMethod(Method method, Class registeredJavaType) {
public RegisteredMethod(Method method, Class<?> registeredJavaType) {
Assert.notNull(method, "Method required");
Assert.notNull(registeredJavaType, "Registered Java Type required");
this.method = method;
@@ -15,23 +15,18 @@
package org.springframework.security.intercept.method;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.SecurityConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.SecurityConfig;
import org.springframework.util.StringUtils;
/**
@@ -44,12 +39,9 @@ import java.util.LinkedHashMap;
* @version $Id$
*/
public class MethodDefinitionSourceEditor extends PropertyEditorSupport {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(MethodDefinitionSourceEditor.class);
//~ Methods ========================================================================================================
@SuppressWarnings("unchecked")
public void setAsText(String s) throws IllegalArgumentException {
if ((s == null) || "".equals(s)) {
setValue(new MapBasedMethodDefinitionSource());
@@ -63,7 +55,7 @@ public class MethodDefinitionSourceEditor extends PropertyEditorSupport {
Properties props = (Properties) propertiesEditor.getValue();
// Now we have properties, process each one individually
Map mappings = new LinkedHashMap();
Map<String, List<ConfigAttribute>> mappings = new LinkedHashMap<String, List<ConfigAttribute>>();
for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
@@ -2,7 +2,6 @@ package org.springframework.security.intercept.method;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -29,25 +28,18 @@ import org.springframework.util.StringUtils;
* having every method of every bean defined in the Spring application context compared with
* those pointcuts. Where a match is found, the matching method will be registered with the
* {@link MapBasedMethodDefinitionSource}.
* </p>
*
* <p>
* It is very important to understand that only the <b>first</b> pointcut that matches a given
* method will be taken as authoritative for that method. This is why pointcuts should be provided
* as a <tt>LinkedHashMap</tt>, because their order is very important.
* </p>
*
* <p>
* Note also that only beans defined in the Spring application context will be examined by this
* class.
* </p>
*
* <p>
* Because this class registers method security metadata with {@link MapBasedMethodDefinitionSource},
* normal Spring Security capabilities such as {@link MethodDefinitionSourceAdvisor} can be used.
* It does not matter the fact the method metadata was originally obtained from an AspectJ pointcut
* expression evaluation.
* </p>
*
* @author Ben Alex
* @verion $Id$
@@ -58,7 +50,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
private static final Log logger = LogFactory.getLog(ProtectPointcutPostProcessor.class);
private Map<String,List<ConfigAttribute>> pointcutMap = new LinkedHashMap();
private Map<String,List<ConfigAttribute>> pointcutMap = new LinkedHashMap<String,List<ConfigAttribute>>();
private MapBasedMethodDefinitionSource mapBasedMethodDefinitionSource;
private PointcutParser parser;
@@ -66,18 +58,18 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
Assert.notNull(mapBasedMethodDefinitionSource, "MapBasedMethodDefinitionSource to populate is required");
this.mapBasedMethodDefinitionSource = mapBasedMethodDefinitionSource;
// Setup AspectJ pointcut expression parser
Set supportedPrimitives = new HashSet();
// Set up AspectJ pointcut expression parser
Set<PointcutPrimitive> supportedPrimitives = new HashSet<PointcutPrimitive>(3);
supportedPrimitives.add(PointcutPrimitive.EXECUTION);
supportedPrimitives.add(PointcutPrimitive.ARGS);
supportedPrimitives.add(PointcutPrimitive.REFERENCE);
// supportedPrimitives.add(PointcutPrimitive.THIS);
// supportedPrimitives.add(PointcutPrimitive.TARGET);
// supportedPrimitives.add(PointcutPrimitive.WITHIN);
// supportedPrimitives.add(PointcutPrimitive.AT_ANNOTATION);
// supportedPrimitives.add(PointcutPrimitive.AT_WITHIN);
// supportedPrimitives.add(PointcutPrimitive.AT_ARGS);
// supportedPrimitives.add(PointcutPrimitive.AT_TARGET);
// supportedPrimitives.add(PointcutPrimitive.THIS);
// supportedPrimitives.add(PointcutPrimitive.TARGET);
// supportedPrimitives.add(PointcutPrimitive.WITHIN);
// supportedPrimitives.add(PointcutPrimitive.AT_ANNOTATION);
// supportedPrimitives.add(PointcutPrimitive.AT_WITHIN);
// supportedPrimitives.add(PointcutPrimitive.AT_ARGS);
// supportedPrimitives.add(PointcutPrimitive.AT_TARGET);
parser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(supportedPrimitives);
}
@@ -96,10 +88,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
// Check to see if any of those methods are compatible with our pointcut expressions
for (int i = 0; i < methods.length; i++) {
Iterator iter = pointcutMap.keySet().iterator();
while (iter.hasNext()) {
String ex = iter.next().toString();
for (String ex : pointcutMap.keySet()) {
// Parse the presented AspectJ pointcut expression
PointcutExpression expression = parser.parsePointcutExpression(ex);
@@ -114,7 +103,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
return bean;
}
private boolean attemptMatch(Class targetClass, Method method, PointcutExpression expression, String beanName) {
private boolean attemptMatch(Class<?> targetClass, Method method, PointcutExpression expression, String beanName) {
// Determine if the presented AspectJ pointcut expression matches this method
boolean matches = expression.matchesMethodExecution(method).alwaysMatches();
@@ -134,9 +123,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
public void setPointcutMap(Map<String, List<ConfigAttribute>> map) {
Assert.notEmpty(map);
Iterator i = map.keySet().iterator();
while (i.hasNext()) {
String expression = i.next().toString();
for (String expression : map.keySet()) {
List<ConfigAttribute> value = map.get(expression);
addPointcut(expression, value);
}
@@ -115,6 +115,7 @@ public class MethodDefinitionSourceAdvisor extends AbstractPointcutAdvisor imple
//~ Inner Classes ==================================================================================================
class MethodDefinitionSourcePointcut extends StaticMethodMatcherPointcut {
@SuppressWarnings("unchecked")
public boolean matches(Method m, Class targetClass) {
return attributeSource.getAttributes(m, targetClass) != null;
}
@@ -49,21 +49,21 @@ public class RequestKey {
}
if (method == null) {
return key.method == null;
return key.method == null;
}
return method.equals(key.method);
}
public String toString() {
StringBuffer sb = new StringBuffer(url.length() + 7);
sb.append("[");
if (method != null) {
sb.append(method).append(",");
}
sb.append(url);
sb.append("]");
return sb.toString();
}
public String toString() {
StringBuffer sb = new StringBuffer(url.length() + 7);
sb.append("[");
if (method != null) {
sb.append(method).append(",");
}
sb.append(url);
sb.append("]");
return sb.toString();
}
}
@@ -29,8 +29,8 @@ import org.apache.commons.logging.LogFactory;
import javax.naming.directory.SearchControls;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@@ -181,7 +181,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);
Set extraRoles = getAdditionalRoles(user, username);
Set<GrantedAuthority> extraRoles = getAdditionalRoles(user, username);
if (extraRoles != null) {
roles.addAll(extraRoles);
@@ -198,28 +198,25 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
}
public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
Set authorities = new HashSet();
if (getGroupSearchBase() == null) {
return authorities;
return Collections.emptySet();
}
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
if (logger.isDebugEnabled()) {
logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
+ groupSearchFilter + " in search base '" + getGroupSearchBase() + "'");
}
Set userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
Set<String> userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
new String[]{userDn, username}, groupRoleAttribute);
if (logger.isDebugEnabled()) {
logger.debug("Roles from search: " + userRoles);
}
Iterator it = userRoles.iterator();
while (it.hasNext()) {
String role = (String) it.next();
for (String role : userRoles) {
if (convertToUpperCase) {
role = role.toUpperCase();
@@ -155,18 +155,18 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
searchControls.setTimeLimit(searchTimeLimit);
}
/**
* Specifies the attributes that will be returned as part of the search.
*<p>
* null indicates that all attributes will be returned.
* An empty array indicates no attributes are returned.
*
* @param attrs An array of attribute names identifying the attributes that
* will be returned. Can be null.
*/
public void setReturningAttributes(String[] attrs) {
searchControls.setReturningAttributes(attrs);
}
/**
* Specifies the attributes that will be returned as part of the search.
*<p>
* null indicates that all attributes will be returned.
* An empty array indicates no attributes are returned.
*
* @param attrs An array of attribute names identifying the attributes that
* will be returned. Can be null.
*/
public void setReturningAttributes(String[] attrs) {
searchControls.setReturningAttributes(attrs);
}
public String toString() {
StringBuffer sb = new StringBuffer();
@@ -81,7 +81,7 @@ public class AnonymousProcessingFilter extends SpringSecurityFilter implements
return auth;
}
protected void doFilterHttp(HttpServletRequest request,HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
protected void doFilterHttp(HttpServletRequest request,HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
boolean addedToken = false;
if (applyAnonymousForThisRequest(request)) {
@@ -109,11 +109,11 @@ public class AnonymousProcessingFilter extends SpringSecurityFilter implements
SecurityContextHolder.getContext().setAuthentication(null);
}
}
}
}
public int getOrder() {
public int getOrder() {
return FilterChainOrder.ANONYMOUS_FILTER;
}
}
public String getKey() {
return key;
@@ -50,7 +50,7 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
Object salt = null;
Object salt = null;
if (this.saltSource != null) {
salt = this.saltSource.getSalt(userDetails);
@@ -143,6 +143,6 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication
*/
public void setIncludeDetailsObject(boolean includeDetailsObject) {
this.includeDetailsObject = includeDetailsObject;
}
}
}
@@ -20,160 +20,160 @@ package org.springframework.security.providers.encoding;
* @author Alan Stewart
*/
class Md4 {
private static final int BLOCK_SIZE = 64;
private static final int HASH_SIZE = 16;
private final byte[] buffer = new byte[BLOCK_SIZE];
private int bufferOffset;
private long byteCount;
private int[] state = new int[4];
private int[] tmp = new int[16];
private static final int BLOCK_SIZE = 64;
private static final int HASH_SIZE = 16;
private final byte[] buffer = new byte[BLOCK_SIZE];
private int bufferOffset;
private long byteCount;
private int[] state = new int[4];
private int[] tmp = new int[16];
Md4() {
reset();
}
Md4() {
reset();
}
public void reset() {
bufferOffset = 0;
byteCount = 0;
state[0] = 0x67452301;
state[1] = 0xEFCDAB89;
state[2] = 0x98BADCFE;
state[3] = 0x10325476;
}
public void reset() {
bufferOffset = 0;
byteCount = 0;
state[0] = 0x67452301;
state[1] = 0xEFCDAB89;
state[2] = 0x98BADCFE;
state[3] = 0x10325476;
}
public byte[] digest() {
byte[] resBuf = new byte[HASH_SIZE];
digest(resBuf, 0, HASH_SIZE);
return resBuf;
}
public byte[] digest() {
byte[] resBuf = new byte[HASH_SIZE];
digest(resBuf, 0, HASH_SIZE);
return resBuf;
}
private void digest(byte[] buffer, int off) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
buffer[off + (i * 4 + j)] = (byte) (state[i] >>> (8 * j));
}
}
}
private void digest(byte[] buffer, int off) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
buffer[off + (i * 4 + j)] = (byte) (state[i] >>> (8 * j));
}
}
}
private void digest(byte[] buffer, int offset, int len) {
this.buffer[this.bufferOffset++] = (byte) 0x80;
int lenOfBitLen = 8;
int C = BLOCK_SIZE - lenOfBitLen;
if (this.bufferOffset > C) {
while (this.bufferOffset < BLOCK_SIZE) {
this.buffer[this.bufferOffset++] = (byte) 0x00;
}
update(this.buffer, 0);
this.bufferOffset = 0;
}
private void digest(byte[] buffer, int offset, int len) {
this.buffer[this.bufferOffset++] = (byte) 0x80;
int lenOfBitLen = 8;
int C = BLOCK_SIZE - lenOfBitLen;
if (this.bufferOffset > C) {
while (this.bufferOffset < BLOCK_SIZE) {
this.buffer[this.bufferOffset++] = (byte) 0x00;
}
update(this.buffer, 0);
this.bufferOffset = 0;
}
while (this.bufferOffset < C) {
this.buffer[this.bufferOffset++] = (byte) 0x00;
}
while (this.bufferOffset < C) {
this.buffer[this.bufferOffset++] = (byte) 0x00;
}
long bitCount = byteCount * 8;
for (int i = 0; i < 64; i += 8) {
this.buffer[this.bufferOffset++] = (byte) (bitCount >>> (i));
}
long bitCount = byteCount * 8;
for (int i = 0; i < 64; i += 8) {
this.buffer[this.bufferOffset++] = (byte) (bitCount >>> (i));
}
update(this.buffer, 0);
digest(buffer, offset);
}
update(this.buffer, 0);
digest(buffer, offset);
}
public void update(byte[] input, int offset, int length) {
byteCount += length;
int todo;
while (length >= (todo = BLOCK_SIZE - this.bufferOffset)) {
System.arraycopy(input, offset, this.buffer, this.bufferOffset, todo);
update(this.buffer, 0);
length -= todo;
offset += todo;
this.bufferOffset = 0;
}
public void update(byte[] input, int offset, int length) {
byteCount += length;
int todo;
while (length >= (todo = BLOCK_SIZE - this.bufferOffset)) {
System.arraycopy(input, offset, this.buffer, this.bufferOffset, todo);
update(this.buffer, 0);
length -= todo;
offset += todo;
this.bufferOffset = 0;
}
System.arraycopy(input, offset, this.buffer, this.bufferOffset, length);
bufferOffset += length;
}
System.arraycopy(input, offset, this.buffer, this.bufferOffset, length);
bufferOffset += length;
}
private void update(byte[] block, int offset) {
for (int i = 0; i < 16; i++) {
tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16 | (block[offset++] & 0xFF) << 24;
}
private void update(byte[] block, int offset) {
for (int i = 0; i < 16; i++) {
tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16 | (block[offset++] & 0xFF) << 24;
}
int A = state[0];
int B = state[1];
int C = state[2];
int D = state[3];
int A = state[0];
int B = state[1];
int C = state[2];
int D = state[3];
A = FF(A, B, C, D, tmp[0], 3);
D = FF(D, A, B, C, tmp[1], 7);
C = FF(C, D, A, B, tmp[2], 11);
B = FF(B, C, D, A, tmp[3], 19);
A = FF(A, B, C, D, tmp[4], 3);
D = FF(D, A, B, C, tmp[5], 7);
C = FF(C, D, A, B, tmp[6], 11);
B = FF(B, C, D, A, tmp[7], 19);
A = FF(A, B, C, D, tmp[8], 3);
D = FF(D, A, B, C, tmp[9], 7);
C = FF(C, D, A, B, tmp[10], 11);
B = FF(B, C, D, A, tmp[11], 19);
A = FF(A, B, C, D, tmp[12], 3);
D = FF(D, A, B, C, tmp[13], 7);
C = FF(C, D, A, B, tmp[14], 11);
B = FF(B, C, D, A, tmp[15], 19);
A = FF(A, B, C, D, tmp[0], 3);
D = FF(D, A, B, C, tmp[1], 7);
C = FF(C, D, A, B, tmp[2], 11);
B = FF(B, C, D, A, tmp[3], 19);
A = FF(A, B, C, D, tmp[4], 3);
D = FF(D, A, B, C, tmp[5], 7);
C = FF(C, D, A, B, tmp[6], 11);
B = FF(B, C, D, A, tmp[7], 19);
A = FF(A, B, C, D, tmp[8], 3);
D = FF(D, A, B, C, tmp[9], 7);
C = FF(C, D, A, B, tmp[10], 11);
B = FF(B, C, D, A, tmp[11], 19);
A = FF(A, B, C, D, tmp[12], 3);
D = FF(D, A, B, C, tmp[13], 7);
C = FF(C, D, A, B, tmp[14], 11);
B = FF(B, C, D, A, tmp[15], 19);
A = GG(A, B, C, D, tmp[0], 3);
D = GG(D, A, B, C, tmp[4], 5);
C = GG(C, D, A, B, tmp[8], 9);
B = GG(B, C, D, A, tmp[12], 13);
A = GG(A, B, C, D, tmp[1], 3);
D = GG(D, A, B, C, tmp[5], 5);
C = GG(C, D, A, B, tmp[9], 9);
B = GG(B, C, D, A, tmp[13], 13);
A = GG(A, B, C, D, tmp[2], 3);
D = GG(D, A, B, C, tmp[6], 5);
C = GG(C, D, A, B, tmp[10], 9);
B = GG(B, C, D, A, tmp[14], 13);
A = GG(A, B, C, D, tmp[3], 3);
D = GG(D, A, B, C, tmp[7], 5);
C = GG(C, D, A, B, tmp[11], 9);
B = GG(B, C, D, A, tmp[15], 13);
A = GG(A, B, C, D, tmp[0], 3);
D = GG(D, A, B, C, tmp[4], 5);
C = GG(C, D, A, B, tmp[8], 9);
B = GG(B, C, D, A, tmp[12], 13);
A = GG(A, B, C, D, tmp[1], 3);
D = GG(D, A, B, C, tmp[5], 5);
C = GG(C, D, A, B, tmp[9], 9);
B = GG(B, C, D, A, tmp[13], 13);
A = GG(A, B, C, D, tmp[2], 3);
D = GG(D, A, B, C, tmp[6], 5);
C = GG(C, D, A, B, tmp[10], 9);
B = GG(B, C, D, A, tmp[14], 13);
A = GG(A, B, C, D, tmp[3], 3);
D = GG(D, A, B, C, tmp[7], 5);
C = GG(C, D, A, B, tmp[11], 9);
B = GG(B, C, D, A, tmp[15], 13);
A = HH(A, B, C, D, tmp[0], 3);
D = HH(D, A, B, C, tmp[8], 9);
C = HH(C, D, A, B, tmp[4], 11);
B = HH(B, C, D, A, tmp[12], 15);
A = HH(A, B, C, D, tmp[2], 3);
D = HH(D, A, B, C, tmp[10], 9);
C = HH(C, D, A, B, tmp[6], 11);
B = HH(B, C, D, A, tmp[14], 15);
A = HH(A, B, C, D, tmp[1], 3);
D = HH(D, A, B, C, tmp[9], 9);
C = HH(C, D, A, B, tmp[5], 11);
B = HH(B, C, D, A, tmp[13], 15);
A = HH(A, B, C, D, tmp[3], 3);
D = HH(D, A, B, C, tmp[11], 9);
C = HH(C, D, A, B, tmp[7], 11);
B = HH(B, C, D, A, tmp[15], 15);
A = HH(A, B, C, D, tmp[0], 3);
D = HH(D, A, B, C, tmp[8], 9);
C = HH(C, D, A, B, tmp[4], 11);
B = HH(B, C, D, A, tmp[12], 15);
A = HH(A, B, C, D, tmp[2], 3);
D = HH(D, A, B, C, tmp[10], 9);
C = HH(C, D, A, B, tmp[6], 11);
B = HH(B, C, D, A, tmp[14], 15);
A = HH(A, B, C, D, tmp[1], 3);
D = HH(D, A, B, C, tmp[9], 9);
C = HH(C, D, A, B, tmp[5], 11);
B = HH(B, C, D, A, tmp[13], 15);
A = HH(A, B, C, D, tmp[3], 3);
D = HH(D, A, B, C, tmp[11], 9);
C = HH(C, D, A, B, tmp[7], 11);
B = HH(B, C, D, A, tmp[15], 15);
state[0] += A;
state[1] += B;
state[2] += C;
state[3] += D;
}
state[0] += A;
state[1] += B;
state[2] += C;
state[3] += D;
}
private int FF(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & c) | (~b & d)) + x;
return t << s | t >>> (32 - s);
}
private int FF(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & c) | (~b & d)) + x;
return t << s | t >>> (32 - s);
}
private int GG(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
return t << s | t >>> (32 - s);
}
private int GG(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
return t << s | t >>> (32 - s);
}
private int HH(int a, int b, int c, int d, int x, int s) {
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
return t << s | t >>> (32 - s);
}
private int HH(int a, int b, int c, int d, int x, int s) {
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
return t << s | t >>> (32 - s);
}
}
@@ -36,52 +36,52 @@ public class Md4PasswordEncoder extends BaseDigestPasswordEncoder {
//~ Methods ========================================================================================================
/**
* Encodes the rawPass using an MD4 message digest. If a salt is specified it will be merged with the password
* Encodes the rawPass using an MD4 message digest. If a salt is specified it will be merged with the password
* before encoding.
*
* @param rawPass The plain text password
* @param salt The salt to sprinkle
* @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled.
*/
public String encodePassword(String rawPass, Object salt) {
String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
byte[] passBytes;
*
* @param rawPass The plain text password
* @param salt The salt to sprinkle
* @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled.
*/
public String encodePassword(String rawPass, Object salt) {
String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
byte[] passBytes;
try {
passBytes = saltedPass.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported!");
}
Md4 md4 = new Md4();
md4.update(passBytes, 0, passBytes.length);
byte[] resBuf = md4.digest();
try {
passBytes = saltedPass.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported!");
}
Md4 md4 = new Md4();
md4.update(passBytes, 0, passBytes.length);
byte[] resBuf = md4.digest();
if (getEncodeHashAsBase64()) {
return new String(Base64.encodeBase64(resBuf));
} else {
return new String(Hex.encodeHex(resBuf));
}
}
if (getEncodeHashAsBase64()) {
return new String(Base64.encodeBase64(resBuf));
} else {
return new String(Hex.encodeHex(resBuf));
}
}
/**
* Takes a previously encoded password and compares it with a raw password after mixing in the salt and
/**
* Takes a previously encoded password and compares it with a raw password after mixing in the salt and
* encoding that value.
*
* @param encPass previously encoded password
* @param rawPass plain text password
* @param salt salt to mix into password
* @return true or false
*/
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
String pass1 = "" + encPass;
String pass2 = encodePassword(rawPass, salt);
return pass1.equals(pass2);
}
*
* @param encPass previously encoded password
* @param rawPass plain text password
* @param salt salt to mix into password
* @return true or false
*/
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
String pass1 = "" + encPass;
String pass2 = encodePassword(rawPass, salt);
return pass1.equals(pass2);
}
public String getAlgorithm() {
return "MD4";
}
public String getAlgorithm() {
return "MD4";
}
}
@@ -74,12 +74,12 @@ public class MessageDigestPasswordEncoder extends BaseDigestPasswordEncoder {
MessageDigest messageDigest = getMessageDigest();
byte[] digest;
try {
digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported!");
}
digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported!");
}
if (getEncodeHashAsBase64()) {
return new String(Base64.encodeBase64(digest));
@@ -21,14 +21,11 @@ import java.util.Set;
/**
* The AuthorityGranter interface is used to map a given principal to role
* names.
*
* <P>
* The AuthorityGranter interface is used to map a given principal to role names.
* <p>
* If a Windows NT login module were to be used from JAAS, an AuthrityGranter
* implementation could be created to map a NT Group Principal to a ROLE_USER
* role for instance. <br>
* </p>
* role for instance.
*
* @author Ray Krueger
* @version $Id$
@@ -40,13 +37,14 @@ public interface AuthorityGranter {
* The grant method is called for each principal returned from the LoginContext subject. If the
* AuthorityGranter wishes to grant any authorities, it should return a java.util.Set containing the role names it
* wishes to grant, such as ROLE_USER. If the AuthrityGranter does not wish to grant any authorities it should
* return null. <br>
* return null.
* <p>
* The set may contain any object as all objects in the returned set will be passed to the JaasGrantedAuthority
* constructor using toString().
*
* @param principal One of the principals from the LoginContext.getSubect().getPrincipals() method.
*
* @return A java.util.Set of role names to grant, or null meaning no roles should be granted for the principal.
* @return the role names to grant, or null, meaning no roles should be granted to the principal.
*/
Set grant(Principal principal);
Set<String> grant(Principal principal);
}
@@ -15,40 +15,11 @@
package org.springframework.security.providers.jaas;
import org.springframework.security.SpringSecurityException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.jaas.event.JaasAuthenticationFailedEvent;
import org.springframework.security.providers.jaas.event.JaasAuthenticationSuccessEvent;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import java.io.IOException;
import java.security.Principal;
import java.security.Security;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.security.auth.callback.Callback;
@@ -58,6 +29,27 @@ import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.SpringSecurityException;
import org.springframework.security.context.HttpSessionSecurityContextRepository;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.jaas.event.JaasAuthenticationFailedEvent;
import org.springframework.security.providers.jaas.event.JaasAuthenticationSuccessEvent;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.springframework.util.Assert;
/**
* An {@link AuthenticationProvider} implementation that retrieves user details from a JAAS login configuration.
@@ -177,64 +169,61 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
* only throws a AuthenticationServiceException, with the message of the LoginException that will be
* thrown, should the loginContext.login() method fail.
*/
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
if (auth instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
public Authentication authenticate(Authentication auth) throws AuthenticationException {
if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
return null;
}
try {
//Create the LoginContext object, and pass our InternallCallbackHandler
LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth));
UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
Set<GrantedAuthority> authorities;
//Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
loginContext.login();
try {
// Create the LoginContext object, and pass our InternallCallbackHandler
LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth));
//create a set to hold the authorities, and add any that have already been applied.
Set<GrantedAuthority> authorities = new HashSet();
// Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
loginContext.login();
if (request.getAuthorities() != null) {
authorities.addAll(request.getAuthorities());
}
// Create a set to hold the authorities, and add any that have already been applied.
authorities = new HashSet<GrantedAuthority>();
//get the subject principals and pass them to each of the AuthorityGranters
Set principals = loginContext.getSubject().getPrincipals();
if (request.getAuthorities() != null) {
authorities.addAll(request.getAuthorities());
}
for (Iterator iterator = principals.iterator(); iterator.hasNext();) {
Principal principal = (Principal) iterator.next();
// Get the subject principals and pass them to each of the AuthorityGranters
Set<Principal> principals = loginContext.getSubject().getPrincipals();
for (int i = 0; i < authorityGranters.length; i++) {
AuthorityGranter granter = authorityGranters[i];
Set roles = granter.grant(principal);
for (Principal principal : principals) {
for (int i = 0; i < authorityGranters.length; i++) {
AuthorityGranter granter = authorityGranters[i];
Set<String> roles = granter.grant(principal);
//If the granter doesn't wish to grant any authorities, it should return null.
if ((roles != null) && !roles.isEmpty()) {
for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();) {
String role = roleIterator.next().toString();
authorities.add(new JaasGrantedAuthority(role, principal));
}
// If the granter doesn't wish to grant any authorities, it should return null.
if ((roles != null) && !roles.isEmpty()) {
for (String role : roles) {
authorities.add(new JaasGrantedAuthority(role, principal));
}
}
}
//Convert the authorities set back to an array and apply it to the token.
JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
request.getCredentials(),
(GrantedAuthority[]) authorities.toArray(new GrantedAuthority[0]), loginContext);
//Publish the success event
publishSuccessEvent(result);
//we're done, return the token.
return result;
} catch (LoginException loginException) {
SpringSecurityException ase = loginExceptionResolver.resolveException(loginException);
publishFailureEvent(request, ase);
throw ase;
}
}
return null;
//Convert the authorities set back to an array and apply it to the token.
JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
request.getCredentials(), new ArrayList<GrantedAuthority>(authorities), loginContext);
//Publish the success event
publishSuccessEvent(result);
//we're done, return the token.
return result;
} catch (LoginException loginException) {
SpringSecurityException ase = loginExceptionResolver.resolveException(loginException);
publishFailureEvent(request, ase);
throw ase;
}
}
/**
@@ -318,13 +307,13 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli
/**
* Handles the logout by getting the SecurityContext for the session that was destroyed. <b>MUST NOT use
* SecurityContextHolder we are logging out a session that is not related to the current user.</b>
* SecurityContextHolder as we are logging out a session that is not related to the current user.</b>
*
* @param event
*/
protected void handleLogout(HttpSessionDestroyedEvent event) {
SecurityContext context = (SecurityContext)
event.getSession().getAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
event.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
if (context == null) {
log.debug("The destroyed session has no SecurityContext");
@@ -15,6 +15,8 @@
package org.springframework.security.providers.jaas;
import java.util.List;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
@@ -40,8 +42,8 @@ public class JaasAuthenticationToken extends UsernamePasswordAuthenticationToken
this.loginContext = loginContext;
}
public JaasAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities,
LoginContext loginContext) {
public JaasAuthenticationToken(Object principal, Object credentials, List<GrantedAuthority> authorities,
LoginContext loginContext) {
super(principal, credentials, authorities);
this.loginContext = loginContext;
}
@@ -32,16 +32,18 @@ import javax.security.auth.spi.LoginModule;
/**
* An implementation of {@link LoginModule} that uses a Spring Security {@link
* org.springframework.security.context.SecurityContext SecurityContext} to provide authentication.<p>This LoginModule
* provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not really be used in
* conjunction with it.</p>
* <p>The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas.</p>
* <p>The SecurityContextLoginModule allows a Jaas based application to authenticate against Spring Security.
* org.springframework.security.context.SecurityContext SecurityContext} to provide authentication.
* <p>
* This LoginModule provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not
* really be used in conjunction with it.
* <p>
* The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas.
* <p>
* The SecurityContextLoginModule allows a Jaas based application to authenticate against Spring Security.
* If there is no Authentication in the {@link SecurityContextHolder} the login() method will throw a LoginException
* by default.
* This functionality can be changed with the <tt>ignoreMissingAuthentication</tt> option by setting it to "true".
* Setting ignoreMissingAuthentication=true will tell the SecurityContextLoginModule to simply return false and be
* ignored if the authentication is null.</p>
* by default. This functionality can be changed with the <tt>ignoreMissingAuthentication</tt> option by setting it
* to "true". Setting ignoreMissingAuthentication=true will tell the SecurityContextLoginModule to simply return false
* and be ignored if the authentication is null.
*
* @author Brian Moseley
* @author Ray Krueger
@@ -107,11 +109,12 @@ public class SecurityContextLoginModule implements LoginModule {
* <code>LoginContext</code> likely won't provide one that understands Spring Security. Also ignores the
* <code>sharedState</code> and <code>options</code> parameters, since none are recognized.
*
* @param subject the <code>Subject</code> to be authenticated. <p>
* @param subject the <code>Subject</code> to be authenticated.
* @param callbackHandler is ignored
* @param sharedState is ignored
* @param options are ignored
*/
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
this.subject = subject;
@@ -15,6 +15,11 @@
package org.springframework.security.providers.ldap.authenticator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ldap.NameNotFoundException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.Authentication;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.ldap.LdapUtils;
@@ -22,16 +27,8 @@ import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.ldap.NameNotFoundException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.util.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Iterator;
/**
* An {@link org.springframework.security.providers.ldap.LdapAuthenticator LdapAuthenticator} which compares the login
@@ -71,17 +68,16 @@ public final class PasswordComparisonAuthenticator extends AbstractLdapAuthentic
String username = authentication.getName();
String password = (String)authentication.getCredentials();
Iterator dns = getUserDns(username).iterator();
SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
while (dns.hasNext() && user == null) {
final String userDn = (String) dns.next();
for (String userDn : getUserDns(username)) {
try {
user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
} catch (NameNotFoundException ignore) {
}
if (user != null) {
break;
}
}
if (user == null && getUserSearch() != null) {
@@ -1,21 +1,17 @@
package org.springframework.security.providers.preauth;
import java.util.Arrays;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsChecker;
import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsChecker;
import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker;
import org.springframework.util.Assert;
/**
@@ -87,8 +83,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
userDetailsChecker.check(ud);
PreAuthenticatedAuthenticationToken result =
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(),
ud.getAuthorities().toArray(new GrantedAuthority[0]));
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities());
result.setDetails(authentication.getDetails());
return result;
@@ -29,11 +29,12 @@ public interface RemoteAuthenticationManager {
/**
* Attempts to authenticate the remote client using the presented username and password. If authentication
* is successful, an array of <code>GrantedAuthority[]</code> objects will be returned.<p>In order to
* maximise remoting protocol compatibility, a design decision was taken to operate with minimal arguments and
* return only the minimal amount of information required for remote clients to enable/disable relevant user
* interface commands etc. There is nothing preventing users from implementing their own equivalent package that
* works with more complex object types.</p>
* is successful, an array of <code>GrantedAuthority[]</code> objects will be returned.
* <p>
* In order to maximise remoting protocol compatibility, a design decision was taken to operate with minimal
* arguments and return only the minimal amount of information required for remote clients to enable/disable
* relevant user interface commands etc. There is nothing preventing users from implementing their own equivalent
* package that works with more complex object types.
*
* @param username the username the remote client wishes to authenticate with.
* @param password the password the remote client wishes to authenticate with.
@@ -15,6 +15,8 @@
package org.springframework.security.providers.rcp;
import java.util.Arrays;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.GrantedAuthority;
@@ -28,11 +30,13 @@ import org.springframework.util.Assert;
/**
* Client-side object which queries a {@link RemoteAuthenticationManager} to validate an authentication request.<p>A
* new <code>Authentication</code> object is created by this class comprising the request <code>Authentication</code>
* Client-side object which queries a {@link RemoteAuthenticationManager} to validate an authentication request.
* <p>
* A new <code>Authentication</code> object is created by this class comprising the request <code>Authentication</code>
* object's <code>principal</code>, <code>credentials</code> and the <code>GrantedAuthority</code>[]s returned by the
* <code>RemoteAuthenticationManager</code>.</p>
* <p>The <code>RemoteAuthenticationManager</code> should not require any special username or password setting on
* <code>RemoteAuthenticationManager</code>.
* <p>
* The <code>RemoteAuthenticationManager</code> should not require any special username or password setting on
* the remoting client proxy factory to execute the call. Instead the entire authentication request must be
* encapsulated solely within the <code>Authentication</code> request object. In practical terms this means the
* <code>RemoteAuthenticationManager</code> will <b>not</b> be protected by BASIC or any other HTTP-level
@@ -50,7 +54,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.remoteAuthenticationManager, "remoteAuthenticationManager is mandatory");
}
@@ -60,7 +64,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini
String password = authentication.getCredentials().toString();
GrantedAuthority[] authorities = remoteAuthenticationManager.attemptAuthentication(username, password);
return new UsernamePasswordAuthenticationToken(username, password, authorities);
return new UsernamePasswordAuthenticationToken(username, password, Arrays.asList(authorities));
}
public RemoteAuthenticationManager getRemoteAuthenticationManager() {
@@ -15,36 +15,25 @@
package org.springframework.security.providers.rememberme;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.AuthenticationProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.util.Assert;
/**
* An {@link AuthenticationProvider} implementation that validates {@link
* org.springframework.security.providers.rememberme.RememberMeAuthenticationToken}s.<p>To be successfully validated, the
* {@link org.springframework.security.providers.rememberme.RememberMeAuthenticationToken#getKeyHash()} must match this class'
* {@link #getKey()}.</p>
* An {@link AuthenticationProvider} implementation that validates {@link RememberMeAuthenticationToken}s.
* <p>
* To be successfully validated, the {@link RememberMeAuthenticationToken#getKeyHash()} must match this class'
* {@link #getKey()}.
*/
public class RememberMeAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(RememberMeAuthenticationProvider.class);
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
@@ -52,13 +41,12 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider,
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
Assert.hasLength(key);
Assert.notNull(this.messages, "A message source must be set");
}
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
@@ -39,6 +39,9 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i
//~ Constructors ===================================================================================================
/**
* @deprecated
*/
public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
this(key, principal, Arrays.asList(authorities));
}
@@ -46,7 +46,7 @@ public class RunAsImplAuthenticationProvider implements InitializingBean, Authen
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
Assert.notNull(key, "A Key is required and should match that configured for the RunAsManagerImpl");
}
@@ -24,6 +24,7 @@ import org.springframework.util.Assert;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -52,35 +53,26 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi
//~ Instance fields ================================================================================================
private List channelProcessors;
private List<ChannelProcessor> channelProcessors;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
checkIfValidList(this.channelProcessors);
Assert.notEmpty(channelProcessors, "A list of ChannelProcessors is required");
}
private void checkIfValidList(List listToCheck) {
Assert.notEmpty(listToCheck, "A list of ChannelProcessors is required");
}
public void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException {
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
throws IOException, ServletException {
Iterator attrs = config.iterator();
Iterator<ConfigAttribute> attrs = config.iterator();
while (attrs.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) attrs.next();
ConfigAttribute attribute = attrs.next();
if (ANY_CHANNEL.equals(attribute.getAttribute())) {
return;
}
}
Iterator iter = this.channelProcessors.iterator();
while (iter.hasNext()) {
ChannelProcessor processor = (ChannelProcessor) iter.next();
for (ChannelProcessor processor : channelProcessors) {
processor.decide(invocation, config);
if (invocation.getResponse().isCommitted()) {
@@ -89,22 +81,20 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi
}
}
protected List getChannelProcessors() {
protected List<ChannelProcessor> getChannelProcessors() {
return this.channelProcessors;
}
public void setChannelProcessors(List newList) {
checkIfValidList(newList);
@SuppressWarnings("cast")
public void setChannelProcessors(List<?> newList) {
Assert.notEmpty(newList, "A list of ChannelProcessors is required");
channelProcessors = new ArrayList<ChannelProcessor>(newList.size());
Iterator iter = newList.iterator();
while (iter.hasNext()) {
Object currentObject = iter.next();
for (Object currentObject : newList) {
Assert.isInstanceOf(ChannelProcessor.class, currentObject, "ChannelProcessor " +
currentObject.getClass().getName() + " must implement ChannelProcessor");
channelProcessors.add((ChannelProcessor)currentObject);
}
this.channelProcessors = newList;
}
public boolean supports(ConfigAttribute attribute) {
@@ -112,11 +102,7 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi
return true;
}
Iterator iter = this.channelProcessors.iterator();
while (iter.hasNext()) {
ChannelProcessor processor = (ChannelProcessor) iter.next();
for (ChannelProcessor processor : channelProcessors) {
if (processor.supports(attribute)) {
return true;
}
@@ -26,17 +26,12 @@ import javax.servlet.ServletException;
/**
* Decides whether a web channel meets a specific security condition.
*
* <P>
* <code>ChannelProcessor</code> implementations are iterated by the {@link
* ChannelDecisionManagerImpl}.
* </p>
*
* <P>
* <p>
* <code>ChannelProcessor</code> implementations are iterated by the {@link ChannelDecisionManagerImpl}.
* <p>
* If an implementation has an issue with the channel security, they should
* take action themselves. The callers of the implementation do not take any
* action.
* </p>
*
* @author Ben Alex
* @version $Id$
@@ -49,16 +44,16 @@ public interface ChannelProcessor {
* security based on the requested list of <tt>ConfigAttribute</tt>s.
*
*/
void decide(FilterInvocation invocation, List<ConfigAttribute> config)
throws IOException, ServletException;
void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException;
/**
* Indicates whether this <code>ChannelProcessor</code> is able to process the passed
* <code>ConfigAttribute</code>.<p>This allows the <code>ChannelProcessingFilter</code> to check every
* configuration attribute can be consumed by the configured <code>ChannelDecisionManager</code>.</p>
* <code>ConfigAttribute</code>.
* <p>
* This allows the <code>ChannelProcessingFilter</code> to check every configuration attribute can be consumed
* by the configured <code>ChannelDecisionManager</code>.
*
* @param attribute a configuration attribute that has been configured against the
* <code>ChannelProcessingFilter</code>
* @param attribute a configuration attribute that has been configured against the <tt>ChannelProcessingFilter</tt>.
*
* @return true if this <code>ChannelProcessor</code> can support the passed configuration attribute
*/
@@ -15,29 +15,26 @@
package org.springframework.security.securechannel;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.intercept.web.FilterInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.intercept.web.FilterInvocation;
import org.springframework.util.Assert;
/**
* <p>Ensures channel security is inactive by review of <code>HttpServletRequest.isSecure()</code> responses.</p>
* <P>The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this keyword is detected,
* Ensures channel security is inactive by review of <code>HttpServletRequest.isSecure()</code> responses.
* <p>
* The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this keyword is detected,
* <code>HttpServletRequest.isSecure()</code> is used to determine the channel security offered. If channel security
* is present, the configured <code>ChannelEntryPoint</code> is called. By default the entry point is {@link
* RetryWithHttpEntryPoint}.</p>
* <P>The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>.</p>
* RetryWithHttpEntryPoint}.
* <p>
* The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>.
*
* @author Ben Alex
* @version $Id$
@@ -55,17 +52,12 @@ public class InsecureChannelProcessor implements InitializingBean, ChannelProces
Assert.notNull(entryPoint, "entryPoint required");
}
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
throws IOException, ServletException {
public void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException {
if ((invocation == null) || (config == null)) {
throw new IllegalArgumentException("Nulls cannot be provided");
}
Iterator iter = config.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) iter.next();
for (ConfigAttribute attribute : config) {
if (supports(attribute)) {
if (invocation.getHttpRequest().isSecure()) {
entryPoint.commence(invocation.getRequest(), invocation.getResponse());
@@ -15,29 +15,26 @@
package org.springframework.security.securechannel;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.intercept.web.FilterInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.intercept.web.FilterInvocation;
import org.springframework.util.Assert;
/**
* <p>Ensures channel security is active by review of <code>HttpServletRequest.isSecure()</code> responses.</p>
* <P>The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this keyword is detected,
* Ensures channel security is active by review of <code>HttpServletRequest.isSecure()</code> responses.
* <p>
* The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this keyword is detected,
* <code>HttpServletRequest.isSecure()</code> is used to determine the channel security offered. If channel security
* is not present, the configured <code>ChannelEntryPoint</code> is called. By default the entry point is {@link
* RetryWithHttpsEntryPoint}.</p>
* <P>The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>.</p>
* RetryWithHttpsEntryPoint}.
* <p>
* The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>.
*
* @author Ben Alex
* @version $Id$
@@ -55,15 +52,10 @@ public class SecureChannelProcessor implements InitializingBean, ChannelProcesso
Assert.notNull(entryPoint, "entryPoint required");
}
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
throws IOException, ServletException {
public void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException {
Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided");
Iterator iter = config.iterator();
while (iter.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) iter.next();
for (ConfigAttribute attribute : config) {
if (supports(attribute)) {
if (!invocation.getHttpRequest().isSecure()) {
entryPoint.commence(invocation.getRequest(), invocation.getResponse());
@@ -11,49 +11,49 @@ import org.springframework.util.Assert;
* @since 2.0.1
*/
public class DefaultToken implements Token {
private String key;
private long keyCreationTime;
private String extendedInformation;
public DefaultToken(String key, long keyCreationTime, String extendedInformation) {
Assert.hasText(key, "Key required");
Assert.notNull(extendedInformation, "Extended information cannot be null");
this.key = key;
this.keyCreationTime = keyCreationTime;
this.extendedInformation = extendedInformation;
}
private String key;
private long keyCreationTime;
private String extendedInformation;
public DefaultToken(String key, long keyCreationTime, String extendedInformation) {
Assert.hasText(key, "Key required");
Assert.notNull(extendedInformation, "Extended information cannot be null");
this.key = key;
this.keyCreationTime = keyCreationTime;
this.extendedInformation = extendedInformation;
}
public String getKey() {
return key;
}
public long getKeyCreationTime() {
return keyCreationTime;
}
public String getKey() {
return key;
}
public long getKeyCreationTime() {
return keyCreationTime;
}
public String getExtendedInformation() {
return extendedInformation;
}
public String getExtendedInformation() {
return extendedInformation;
}
public boolean equals(Object obj) {
if (obj != null && obj instanceof DefaultToken) {
DefaultToken rhs = (DefaultToken) obj;
return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime && this.extendedInformation.equals(rhs.extendedInformation);
}
return false;
}
public boolean equals(Object obj) {
if (obj != null && obj instanceof DefaultToken) {
DefaultToken rhs = (DefaultToken) obj;
return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime && this.extendedInformation.equals(rhs.extendedInformation);
}
return false;
}
public int hashCode() {
public int hashCode() {
int code = 979;
code = code * key.hashCode();
code = code * new Long(keyCreationTime).hashCode();
code = code * extendedInformation.hashCode();
return code;
}
}
public String toString() {
return "DefaultToken[key=" + new String(key) + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]";
}
public String toString() {
return "DefaultToken[key=" + new String(key) + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]";
}
}
@@ -54,117 +54,117 @@ import org.springframework.util.StringUtils;
*
*/
public class KeyBasedPersistenceTokenService implements TokenService, InitializingBean {
private int pseudoRandomNumberBits = 256;
private String serverSecret;
private Integer serverInteger;
private SecureRandom secureRandom;
public Token allocateToken(String extendedInformation) {
Assert.notNull(extendedInformation, "Must provided non-null extendedInformation (but it can be empty)");
long creationTime = new Date().getTime();
String serverSecret = computeServerSecretApplicableAt(creationTime);
String pseudoRandomNumber = generatePseudoRandomNumber();
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation;
private int pseudoRandomNumberBits = 256;
private String serverSecret;
private Integer serverInteger;
private SecureRandom secureRandom;
public Token allocateToken(String extendedInformation) {
Assert.notNull(extendedInformation, "Must provided non-null extendedInformation (but it can be empty)");
long creationTime = new Date().getTime();
String serverSecret = computeServerSecretApplicableAt(creationTime);
String pseudoRandomNumber = generatePseudoRandomNumber();
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation;
// Compute key
String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
String keyPayload = content + ":" + sha512Hex;
String key = convertToString(Base64.encodeBase64(convertToBytes(keyPayload)));
return new DefaultToken(key, creationTime, extendedInformation);
}
// Compute key
String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
String keyPayload = content + ":" + sha512Hex;
String key = convertToString(Base64.encodeBase64(convertToBytes(keyPayload)));
return new DefaultToken(key, creationTime, extendedInformation);
}
public Token verifyToken(String key) {
if (key == null || "".equals(key)) {
return null;
}
String[] tokens = StringUtils.delimitedListToStringArray(convertToString(Base64.decodeBase64(convertToBytes(key))), ":");
Assert.isTrue(tokens.length >= 4, "Expected 4 or more tokens but found " + tokens.length);
long creationTime;
try {
creationTime = Long.decode(tokens[0]).longValue();
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Expected number but found " + tokens[0]);
}
String serverSecret = computeServerSecretApplicableAt(creationTime);
String pseudoRandomNumber = tokens[1];
// Permit extendedInfo to itself contain ":" characters
StringBuffer extendedInfo = new StringBuffer();
for (int i = 2; i < tokens.length-1; i++) {
if (i > 2) {
extendedInfo.append(":");
}
extendedInfo.append(tokens[i]);
}
String sha1Hex = tokens[tokens.length-1];
// Verification
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure");
return new DefaultToken(key, creationTime, extendedInfo.toString());
}
private byte[] convertToBytes(String input) {
try {
return input.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String convertToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @return a pseduo random number (hex encoded)
*/
private String generatePseudoRandomNumber() {
byte[] randomizedBits = new byte[pseudoRandomNumberBits];
secureRandom.nextBytes(randomizedBits);
return new String(Hex.encodeHex(randomizedBits));
}
private String computeServerSecretApplicableAt(long time) {
return serverSecret + ":" + new Long(time % serverInteger.intValue()).intValue();
}
public Token verifyToken(String key) {
if (key == null || "".equals(key)) {
return null;
}
String[] tokens = StringUtils.delimitedListToStringArray(convertToString(Base64.decodeBase64(convertToBytes(key))), ":");
Assert.isTrue(tokens.length >= 4, "Expected 4 or more tokens but found " + tokens.length);
long creationTime;
try {
creationTime = Long.decode(tokens[0]).longValue();
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Expected number but found " + tokens[0]);
}
String serverSecret = computeServerSecretApplicableAt(creationTime);
String pseudoRandomNumber = tokens[1];
// Permit extendedInfo to itself contain ":" characters
StringBuffer extendedInfo = new StringBuffer();
for (int i = 2; i < tokens.length-1; i++) {
if (i > 2) {
extendedInfo.append(":");
}
extendedInfo.append(tokens[i]);
}
String sha1Hex = tokens[tokens.length-1];
// Verification
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure");
return new DefaultToken(key, creationTime, extendedInfo.toString());
}
private byte[] convertToBytes(String input) {
try {
return input.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String convertToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @return a pseduo random number (hex encoded)
*/
private String generatePseudoRandomNumber() {
byte[] randomizedBits = new byte[pseudoRandomNumberBits];
secureRandom.nextBytes(randomizedBits);
return new String(Hex.encodeHex(randomizedBits));
}
private String computeServerSecretApplicableAt(long time) {
return serverSecret + ":" + new Long(time % serverInteger.intValue()).intValue();
}
/**
* @param serverSecret the new secret, which can contain a ":" if desired (never being sent to the client)
*/
public void setServerSecret(String serverSecret) {
this.serverSecret = serverSecret;
}
public void setSecureRandom(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
}
/**
* @param pseudoRandomNumberBits changes the number of bits issued (must be >= 0; defaults to 256)
*/
public void setPseudoRandomNumberBits(int pseudoRandomNumberBits) {
Assert.isTrue(pseudoRandomNumberBits >= 0, "Must have a positive pseudo random number bit size");
this.pseudoRandomNumberBits = pseudoRandomNumberBits;
}
/**
* @param serverSecret the new secret, which can contain a ":" if desired (never being sent to the client)
*/
public void setServerSecret(String serverSecret) {
this.serverSecret = serverSecret;
}
public void setSecureRandom(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
}
/**
* @param pseudoRandomNumberBits changes the number of bits issued (must be >= 0; defaults to 256)
*/
public void setPseudoRandomNumberBits(int pseudoRandomNumberBits) {
Assert.isTrue(pseudoRandomNumberBits >= 0, "Must have a positive pseudo random number bit size");
this.pseudoRandomNumberBits = pseudoRandomNumberBits;
}
public void setServerInteger(Integer serverInteger) {
this.serverInteger = serverInteger;
}
public void setServerInteger(Integer serverInteger) {
this.serverInteger = serverInteger;
}
public void afterPropertiesSet() throws Exception {
Assert.hasText(serverSecret, "Server secret required");
Assert.notNull(serverInteger, "Server integer required");
Assert.notNull(secureRandom, "SecureRandom instance required");
}
public void afterPropertiesSet() throws Exception {
Assert.hasText(serverSecret, "Server secret required");
Assert.notNull(serverInteger, "Server integer required");
Assert.notNull(secureRandom, "SecureRandom instance required");
}
}
@@ -10,60 +10,59 @@ import org.springframework.util.FileCopyUtils;
/**
* Creates a {@link SecureRandom} instance.
*
*
* @author Ben Alex
* @since 2.0.1
*
* @version $Id$
*/
public class SecureRandomFactoryBean implements FactoryBean {
public class SecureRandomFactoryBean implements FactoryBean<SecureRandom> {
private String algorithm = "SHA1PRNG";
private Resource seed;
public Object getObject() throws Exception {
SecureRandom rnd = SecureRandom.getInstance(algorithm);
if (seed != null) {
// Seed specified, so use it
byte[] seedBytes = FileCopyUtils.copyToByteArray(seed.getInputStream());
rnd.setSeed(seedBytes);
} else {
// Request the next bytes, thus eagerly incurring the expense of default seeding
rnd.nextBytes(new byte[1]);
}
return rnd;
}
private String algorithm = "SHA1PRNG";
private Resource seed;
public Class getObjectType() {
return SecureRandom.class;
}
public SecureRandom getObject() throws Exception {
SecureRandom rnd = SecureRandom.getInstance(algorithm);
public boolean isSingleton() {
return false;
}
if (seed != null) {
// Seed specified, so use it
byte[] seedBytes = FileCopyUtils.copyToByteArray(seed.getInputStream());
rnd.setSeed(seedBytes);
} else {
// Request the next bytes, thus eagerly incurring the expense of default seeding
rnd.nextBytes(new byte[1]);
}
/**
* Allows the Pseudo Random Number Generator (PRNG) algorithm to be nominated. Defaults to
* SHA1PRNG.
*
* @param algorithm to use (mandatory)
*/
public void setAlgorithm(String algorithm) {
Assert.hasText(algorithm, "Algorithm required");
this.algorithm = algorithm;
}
return rnd;
}
/**
* Allows the user to specify a resource which will act as a seed for the {@link SecureRandom}
* instance. Specifically, the resource will be read into an {@link InputStream} and those
* bytes presented to the {@link SecureRandom#setSeed(byte[])} method. Note that this will
* simply supplement, rather than replace, the existing seed. As such, it is always safe to
* set a seed using this method (it never reduces randomness).
*
* @param seed to use, or <code>null</code> if no additional seeding is needed
*/
public void setSeed(Resource seed) {
this.seed = seed;
}
public Class<SecureRandom> getObjectType() {
return SecureRandom.class;
}
public boolean isSingleton() {
return false;
}
/**
* Allows the Pseudo Random Number Generator (PRNG) algorithm to be nominated. Defaults to "SHA1PRNG".
*
* @param algorithm to use (mandatory)
*/
public void setAlgorithm(String algorithm) {
Assert.hasText(algorithm, "Algorithm required");
this.algorithm = algorithm;
}
/**
* Allows the user to specify a resource which will act as a seed for the {@link SecureRandom}
* instance. Specifically, the resource will be read into an {@link InputStream} and those
* bytes presented to the {@link SecureRandom#setSeed(byte[])} method. Note that this will
* simply supplement, rather than replace, the existing seed. As such, it is always safe to
* set a seed using this method (it never reduces randomness).
*
* @param seed to use, or <code>null</code> if no additional seeding is needed
*/
public void setSeed(Resource seed) {
this.seed = seed;
}
}
@@ -16,30 +16,30 @@ package org.springframework.security.token;
* @since 2.0.1
*/
public interface Token {
/**
* Obtains the randomised, secure key assigned to this token. Presentation of this token to
* {@link TokenService} will always return a <code>Token</code> that is equal to the original
* <code>Token</code> issued for that key.
*
* @return a key with appropriate randomness and security.
*/
String getKey();
/**
* The time the token key was initially created is available from this method. Note that a given
* token must never have this creation time changed. If necessary, a new token can be
* requested from the {@link TokenService} to replace the original token.
*
* @return the time this token key was created, in the same format as specified by {@link Date#getTime()).
*/
long getKeyCreationTime();
/**
* Obtains the extended information associated within the token, which was presented when the token
* was first created.
*
* @return the user-specified extended information, if any
*/
String getExtendedInformation();
/**
* Obtains the randomised, secure key assigned to this token. Presentation of this token to
* {@link TokenService} will always return a <code>Token</code> that is equal to the original
* <code>Token</code> issued for that key.
*
* @return a key with appropriate randomness and security.
*/
String getKey();
/**
* The time the token key was initially created is available from this method. Note that a given
* token must never have this creation time changed. If necessary, a new token can be
* requested from the {@link TokenService} to replace the original token.
*
* @return the time this token key was created, in the same format as specified by {@link Date#getTime()).
*/
long getKeyCreationTime();
/**
* Obtains the extended information associated within the token, which was presented when the token
* was first created.
*
* @return the user-specified extended information, if any
*/
String getExtendedInformation();
}
@@ -26,21 +26,21 @@ package org.springframework.security.token;
*
*/
public interface TokenService {
/**
* Forces the allocation of a new {@link Token}.
*
* @param the extended information desired in the token (cannot be <code>null</code>, but can be empty)
* @return a new token that has not been issued previously, and is guaranteed to be recognised
* by this implementation's {@link #verifyToken(String)} at any future time.
*/
Token allocateToken(String extendedInformation);
/**
* Permits verification the <{@link Token#getKey()} was issued by this <code>TokenService</code> and
* reconstructs the corresponding <code>Token</code>.
*
* @param key as obtained from {@link Token#getKey()} and created by this implementation
* @return the token, or <code>null</code> if the token was not issued by this <code>TokenService</code>
*/
Token verifyToken(String key);
/**
* Forces the allocation of a new {@link Token}.
*
* @param the extended information desired in the token (cannot be <code>null</code>, but can be empty)
* @return a new token that has not been issued previously, and is guaranteed to be recognised
* by this implementation's {@link #verifyToken(String)} at any future time.
*/
Token allocateToken(String extendedInformation);
/**
* Permits verification the <{@link Token#getKey()} was issued by this <code>TokenService</code> and
* reconstructs the corresponding <code>Token</code>.
*
* @param key as obtained from {@link Token#getKey()} and created by this implementation
* @return the token, or <code>null</code> if the token was not issued by this <code>TokenService</code>
*/
Token verifyToken(String key);
}
@@ -1,8 +1,6 @@
package org.springframework.security.ui;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -174,7 +174,7 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi
chain.doFilter(request, response);
}
private boolean authenticationIsRequired(String username) {
private boolean authenticationIsRequired(String username) {
// Only reauthenticate if username doesn't match SecurityContextHolder and user isn't authenticated
// (see SEC-53)
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
@@ -198,12 +198,12 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi
// both of which force re-authentication if the respective header is detected (and in doing so replace
// any existing AnonymousAuthenticationToken). See SEC-610.
if (existingAuth instanceof AnonymousAuthenticationToken) {
return true;
return true;
}
return false;
}
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException {
}
@@ -242,20 +242,20 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi
}
public void setRememberMeServices(RememberMeServices rememberMeServices) {
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
this.rememberMeServices = rememberMeServices;
}
public void setCredentialsCharset(String credentialsCharset) {
Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
this.credentialsCharset = credentialsCharset;
}
Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
this.credentialsCharset = credentialsCharset;
}
protected String getCredentialsCharset(HttpServletRequest httpRequest) {
return credentialsCharset;
}
return credentialsCharset;
}
public int getOrder() {
public int getOrder() {
return FilterChainOrder.BASIC_PROCESSING_FILTER;
}
}
@@ -44,8 +44,8 @@ public class BasicProcessingFilterEntryPoint implements AuthenticationEntryPoint
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasText(realmName, "realmName must be specified");
public void afterPropertiesSet() throws Exception {
Assert.hasText(realmName, "realmName must be specified");
}
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
@@ -57,14 +57,14 @@ public class DigestProcessingFilterEntryPoint implements AuthenticationEntryPoin
//~ Methods ========================================================================================================
public int getOrder() {
return order;
}
return order;
}
public void setOrder(int order) {
this.order = order;
}
public void setOrder(int order) {
this.order = order;
}
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
if ((realmName == null) || "".equals(realmName)) {
throw new IllegalArgumentException("realmName must be specified");
}
@@ -99,7 +99,7 @@ public abstract class AbstractPreAuthenticatedProcessingFilter extends SpringSec
unsuccessfulAuthentication(request, response, failed);
if (!continueFilterChainOnUnsuccessfulAuthentication) {
throw failed;
throw failed;
}
}
}
@@ -158,7 +158,7 @@ public abstract class AbstractPreAuthenticatedProcessingFilter extends SpringSec
}
public void setContinueFilterChainOnUnsuccessfulAuthentication(boolean shouldContinue) {
continueFilterChainOnUnsuccessfulAuthentication = shouldContinue;
continueFilterChainOnUnsuccessfulAuthentication = shouldContinue;
}
/**
@@ -4,8 +4,8 @@ import org.springframework.security.AuthenticationException;
public class PreAuthenticatedCredentialsNotFoundException extends AuthenticationException {
public PreAuthenticatedCredentialsNotFoundException(String msg) {
super(msg);
}
public PreAuthenticatedCredentialsNotFoundException(String msg) {
super(msg);
}
}
@@ -18,27 +18,27 @@ import org.springframework.security.MutableGrantedAuthoritiesContainer;
* @since 2.0
*/
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails extends WebAuthenticationDetails implements
MutableGrantedAuthoritiesContainer {
public static final long serialVersionUID = 1L;
MutableGrantedAuthoritiesContainer {
public static final long serialVersionUID = 1L;
private MutableGrantedAuthoritiesContainer authoritiesContainer = new GrantedAuthoritiesContainerImpl();
private MutableGrantedAuthoritiesContainer authoritiesContainer = new GrantedAuthoritiesContainerImpl();
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request) {
super(request);
}
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request) {
super(request);
}
public List<GrantedAuthority> getGrantedAuthorities() {
return authoritiesContainer.getGrantedAuthorities();
}
public List<GrantedAuthority> getGrantedAuthorities() {
return authoritiesContainer.getGrantedAuthorities();
}
public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
this.authoritiesContainer.setGrantedAuthorities(authorities);
}
public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
this.authoritiesContainer.setGrantedAuthorities(authorities);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString() + "; ");
sb.append(authoritiesContainer);
return sb.toString();
}
}
}
@@ -38,28 +38,28 @@ import org.springframework.core.Ordered;
* @since 2.0
*/
public class PreAuthenticatedProcessingFilterEntryPoint implements AuthenticationEntryPoint, Ordered {
private static final Log logger = LogFactory.getLog(PreAuthenticatedProcessingFilterEntryPoint.class);
private static final Log logger = LogFactory.getLog(PreAuthenticatedProcessingFilterEntryPoint.class);
private int order = Integer.MAX_VALUE;
private int order = Integer.MAX_VALUE;
/**
* Always returns a 403 error code to the client.
*/
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-authenticated entry point called. Rejecting access");
}
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
/**
* Always returns a 403 error code to the client.
*/
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-authenticated entry point called. Rejecting access");
}
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
public int getOrder() {
return order;
}
public int getOrder() {
return order;
}
public void setOrder(int i) {
order = i;
}
public void setOrder(int i) {
order = i;
}
}
@@ -27,50 +27,50 @@ import org.springframework.util.Assert;
* @since 2.0
*/
public class RequestHeaderPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
private String principalRequestHeader = "SM_USER";
private String credentialsRequestHeader;
private String principalRequestHeader = "SM_USER";
private String credentialsRequestHeader;
/**
* Read and returns the header named by <tt>principalRequestHeader</tt> from the request.
*
* @throws PreAuthenticatedCredentialsNotFoundException if the header is missing
*/
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
String principal = request.getHeader(principalRequestHeader);
if (principal == null) {
throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader
+ " header not found in request.");
}
/**
* Read and returns the header named by <tt>principalRequestHeader</tt> from the request.
*
* @throws PreAuthenticatedCredentialsNotFoundException if the header is missing
*/
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
String principal = request.getHeader(principalRequestHeader);
if (principal == null) {
throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader
+ " header not found in request.");
}
return principal;
}
/**
* Credentials aren't usually applicable, but if a <tt>credentialsRequestHeader</tt> is set, this
* will be read and used as the credentials value. Otherwise a dummy value will be used.
*/
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
if (credentialsRequestHeader != null) {
String credentials = request.getHeader(credentialsRequestHeader);
return credentials;
}
return principal;
}
/**
* Credentials aren't usually applicable, but if a <tt>credentialsRequestHeader</tt> is set, this
* will be read and used as the credentials value. Otherwise a dummy value will be used.
*/
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
if (credentialsRequestHeader != null) {
String credentials = request.getHeader(credentialsRequestHeader);
return credentials;
}
return "N/A";
}
public void setPrincipalRequestHeader(String principalRequestHeader) {
Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null");
this.principalRequestHeader = principalRequestHeader;
}
return "N/A";
}
public void setPrincipalRequestHeader(String principalRequestHeader) {
Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null");
this.principalRequestHeader = principalRequestHeader;
}
public void setCredentialsRequestHeader(String credentialsRequestHeader) {
Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null");
this.credentialsRequestHeader = credentialsRequestHeader;
}
public void setCredentialsRequestHeader(String credentialsRequestHeader) {
Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null");
this.credentialsRequestHeader = credentialsRequestHeader;
}
public int getOrder() {
return FilterChainOrder.PRE_AUTH_FILTER;
}
public int getOrder() {
return FilterChainOrder.PRE_AUTH_FILTER;
}
}
@@ -15,10 +15,10 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* WebSphere Security helper class to allow retrieval of the current username and groups.
* WebSphere Security helper class to allow retrieval of the current username and groups.
* <p>
* See Spring Security JIRA SEC-477.
*
* See Spring Security Jira SEC-477.
*
* @author Ruud Senden
* @author Stephane Manciot
* @since 2.0
@@ -35,11 +35,11 @@ final class WASSecurityHelper {
private static Method getSecurityName = null;
// SEC-803
private static Class wsCredentialClass = null;
private static Class<?> wsCredentialClass = null;
/**
* Get the security name for the given subject.
*
*
* @param subject
* The subject for which to retrieve the security name
* @return String the security name for the given subject
@@ -64,7 +64,7 @@ final class WASSecurityHelper {
/**
* Get the current RunAs subject.
*
*
* @return Subject the current RunAs subject
*/
private static final Subject getRunAsSubject() {
@@ -75,7 +75,7 @@ final class WASSecurityHelper {
/**
* Get the WebSphere group names for the given subject.
*
*
* @param subject
* The subject for which to retrieve the WebSphere group names
* @return the WebSphere group names for the given subject
@@ -86,11 +86,12 @@ final class WASSecurityHelper {
/**
* Get the WebSphere group names for the given security name.
*
*
* @param securityName
* The securityname for which to retrieve the WebSphere group names
* @return the WebSphere group names for the given security name
*/
@SuppressWarnings("unchecked")
private static final String[] getWebSphereGroups(final String securityName) {
Context ic = null;
try {
@@ -129,7 +130,7 @@ final class WASSecurityHelper {
public static final String getCurrentUserName() {
return getSecurityName(getRunAsSubject());
}
private static final Object invokeMethod(Method method, Object instance, Object[] args)
{
try {
@@ -148,9 +149,9 @@ final class WASSecurityHelper {
private static final Method getMethod(String className, String methodName, String[] parameterTypeNames) {
try {
Class c = Class.forName(className);
Class<?> c = Class.forName(className);
final int len = parameterTypeNames.length;
Class[] parameterTypes = new Class[len];
Class<?>[] parameterTypes = new Class[len];
for (int i = 0; i < len; i++) {
parameterTypes[i] = Class.forName(parameterTypeNames[i]);
}
@@ -162,7 +163,7 @@ final class WASSecurityHelper {
logger.error("Required method "+methodName+" with parameter types ("+ Arrays.asList(parameterTypeNames) +") not found on class "+className);
throw new RuntimeException("Required class"+className+" not found",e);
}
}
}
private static final Method getRunAsSubjectMethod() {
if (getRunAsSubject == null) {
@@ -184,22 +185,22 @@ final class WASSecurityHelper {
}
return getSecurityName;
}
// SEC-803
private static final Class getWSCredentialClass() {
private static final Class<?> getWSCredentialClass() {
if (wsCredentialClass == null) {
wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential");
}
return wsCredentialClass;
}
private static final Class getClass(String className) {
private static final Class<?> getClass(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
logger.error("Required class " + className + " not found");
throw new RuntimeException("Required class " + className + " not found",e);
}
}
}
}
@@ -19,78 +19,78 @@ import org.springframework.util.Assert;
* @since 1.0
*/
public class WebSphere2SpringSecurityPropagationInterceptor implements MethodInterceptor {
private static final Log LOG = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class);
private AuthenticationManager authenticationManager = null;
private AuthenticationDetailsSource authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource();
/**
* Authenticate with Spring Security based on WebSphere credentials before proceeding with method
* invocation, and clean up the Spring Security Context after method invocation finishes.
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
try {
LOG.debug("Performing Spring Security authentication with WebSphere credentials");
authenticateSpringSecurityWithWASCredentials(this);
LOG.debug("Proceeding with method invocation");
return methodInvocation.proceed();
} finally {
LOG.debug("Clearing Spring Security security context");
clearSpringSecurityContext();
}
}
/**
* Retrieve the current WebSphere credentials and authenticate them with Spring Security
* using the pre-authenticated authentication provider.
* @param aContext The context to use for building the authentication details.
*/
private final void authenticateSpringSecurityWithWASCredentials(Object aContext)
{
Assert.notNull(authenticationManager);
Assert.notNull(authenticationDetailsSource);
String userName = WASSecurityHelper.getCurrentUserName();
if (LOG.isDebugEnabled()) { LOG.debug("Creating authentication request for user "+userName); }
PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName,null);
authRequest.setDetails(authenticationDetailsSource.buildDetails(null));
if (LOG.isDebugEnabled()) { LOG.debug("Authentication request for user "+userName+": "+authRequest); }
Authentication authResponse = authenticationManager.authenticate(authRequest);
if (LOG.isDebugEnabled()) { LOG.debug("Authentication response for user "+userName+": "+authResponse); }
SecurityContextHolder.getContext().setAuthentication(authResponse);
}
/**
* Clear the Spring Security Context
*/
private final void clearSpringSecurityContext()
{
SecurityContextHolder.clearContext();
}
private static final Log LOG = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class);
private AuthenticationManager authenticationManager = null;
private AuthenticationDetailsSource authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource();
/**
* Authenticate with Spring Security based on WebSphere credentials before proceeding with method
* invocation, and clean up the Spring Security Context after method invocation finishes.
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
try {
LOG.debug("Performing Spring Security authentication with WebSphere credentials");
authenticateSpringSecurityWithWASCredentials(this);
LOG.debug("Proceeding with method invocation");
return methodInvocation.proceed();
} finally {
LOG.debug("Clearing Spring Security security context");
clearSpringSecurityContext();
}
}
/**
* Retrieve the current WebSphere credentials and authenticate them with Spring Security
* using the pre-authenticated authentication provider.
* @param aContext The context to use for building the authentication details.
*/
private final void authenticateSpringSecurityWithWASCredentials(Object aContext)
{
Assert.notNull(authenticationManager);
Assert.notNull(authenticationDetailsSource);
String userName = WASSecurityHelper.getCurrentUserName();
if (LOG.isDebugEnabled()) { LOG.debug("Creating authentication request for user "+userName); }
PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName,null);
authRequest.setDetails(authenticationDetailsSource.buildDetails(null));
if (LOG.isDebugEnabled()) { LOG.debug("Authentication request for user "+userName+": "+authRequest); }
Authentication authResponse = authenticationManager.authenticate(authRequest);
if (LOG.isDebugEnabled()) { LOG.debug("Authentication response for user "+userName+": "+authResponse); }
SecurityContextHolder.getContext().setAuthentication(authResponse);
}
/**
* Clear the Spring Security Context
*/
private final void clearSpringSecurityContext()
{
SecurityContextHolder.clearContext();
}
/**
* @return Returns the authenticationManager.
*/
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* @param authenticationManager The authenticationManager to set.
*/
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* @return Returns the authenticationDetailsSource.
*/
public AuthenticationDetailsSource getAuthenticationDetailsSource() {
return authenticationDetailsSource;
}
/**
* @param authenticationDetailsSource The authenticationDetailsSource to set.
*/
public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
this.authenticationDetailsSource = authenticationDetailsSource;
}
/**
* @return Returns the authenticationManager.
*/
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* @param authenticationManager The authenticationManager to set.
*/
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* @return Returns the authenticationDetailsSource.
*/
public AuthenticationDetailsSource getAuthenticationDetailsSource() {
return authenticationDetailsSource;
}
/**
* @param authenticationDetailsSource The authenticationDetailsSource to set.
*/
public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
this.authenticationDetailsSource = authenticationDetailsSource;
}
}
@@ -70,8 +70,7 @@ public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends Authen
List<String> webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser());
List<GrantedAuthority> userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
if (logger.isDebugEnabled()) {
logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: "
+ Arrays.asList(userGas));
logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " + userGas);
}
return userGas;
}
@@ -13,12 +13,12 @@ import org.springframework.security.ui.preauth.PreAuthenticatedGrantedAuthoritie
* @author Ruud Senden
*/
public class WebSpherePreAuthenticatedWebAuthenticationDetailsSource extends WebSpherePreAuthenticatedAuthenticationDetailsSource {
/**
* Public constructor which overrides the default AuthenticationDetails
* class to be used.
*/
public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() {
super();
super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
}
/**
* Public constructor which overrides the default AuthenticationDetails
* class to be used.
*/
public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() {
super();
super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
}
}
@@ -8,16 +8,16 @@ import java.util.Iterator;
import java.util.Map;
/**
* Simple <tt>PersistentTokenRepository</tt> implementation backed by a Map. Intended for testing only.
* Simple <tt>PersistentTokenRepository</tt> implementation backed by a Map. Intended for testing only.
*
* @author Luke Taylor
* @version $Id$
*/
public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
private Map seriesTokens = new HashMap();
private Map<String, PersistentRememberMeToken> seriesTokens = new HashMap<String, PersistentRememberMeToken>();
public synchronized void createNewToken(PersistentRememberMeToken token) {
PersistentRememberMeToken current = (PersistentRememberMeToken) seriesTokens.get(token.getSeries());
PersistentRememberMeToken current = seriesTokens.get(token.getSeries());
if (current != null) {
throw new DataIntegrityViolationException("Series Id '"+ token.getSeries() +"' already exists!");
@@ -41,7 +41,7 @@ public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
}
public synchronized void removeUserTokens(String username) {
Iterator series = seriesTokens.keySet().iterator();
Iterator<String> series = seriesTokens.keySet().iterator();
while (series.hasNext()) {
Object seriesId = series.next();
@@ -48,10 +48,10 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
private String removeUserTokensSql = DEF_REMOVE_USER_TOKENS_SQL;
private boolean createTableOnStartup;
protected MappingSqlQuery tokensBySeriesMapping;
protected SqlUpdate insertToken;
protected SqlUpdate updateToken;
protected SqlUpdate removeUserTokens;
private MappingSqlQuery<PersistentRememberMeToken> tokensBySeriesMapping;
private SqlUpdate insertToken;
private SqlUpdate updateToken;
private SqlUpdate removeUserTokens;
protected void initDao() {
tokensBySeriesMapping = new TokensBySeriesMapping(getDataSource());
@@ -111,14 +111,14 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
//~ Inner Classes ==================================================================================================
protected class TokensBySeriesMapping extends MappingSqlQuery {
private class TokensBySeriesMapping extends MappingSqlQuery<PersistentRememberMeToken> {
protected TokensBySeriesMapping(DataSource ds) {
super(ds, tokensBySeriesSql);
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {
protected PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) throws SQLException {
PersistentRememberMeToken token =
new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4));
@@ -126,7 +126,7 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
}
}
protected class UpdateToken extends SqlUpdate {
private class UpdateToken extends SqlUpdate {
public UpdateToken(DataSource ds) {
super(ds, updateTokenSql);
@@ -138,7 +138,7 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
}
}
protected class InsertToken extends SqlUpdate {
private class InsertToken extends SqlUpdate {
public InsertToken(DataSource ds) {
super(ds, insertTokenSql);
@@ -150,7 +150,7 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
}
}
protected class RemoveUserTokens extends SqlUpdate {
private class RemoveUserTokens extends SqlUpdate {
public RemoveUserTokens(DataSource ds) {
super(ds, removeUserTokensSql);
declareParameter(new SqlParameter(Types.VARCHAR));
@@ -63,9 +63,9 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "authenticationManager must be specified");
Assert.notNull(rememberMeServices, "rememberMeServices must be specified");
}
Assert.notNull(authenticationManager, "authenticationManager must be specified");
Assert.notNull(rememberMeServices, "rememberMeServices must be specified");
}
public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
@@ -76,7 +76,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
if (rememberMeAuth != null) {
// Attempt authenticaton via AuthenticationManager
try {
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
// Store to SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
@@ -122,7 +122,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
* <tt>autoLogin</tt> method and the <tt>AuthenticationManager</tt>.
*/
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) {
Authentication authResult) {
}
/**
@@ -131,7 +131,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
* token is present in the request and <tt>autoLogin</tt> returns null.
*/
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) {
AuthenticationException failed) {
}
public RememberMeServices getRememberMeServices() {
@@ -26,8 +26,9 @@ import java.util.TimeZone;
/**
* <p>Utility class to generate HTTP dates.</p>
* <p>This class is based on code in Apache Tomcat.</p>
* Utility class to generate HTTP dates.
* <p>
* This class is based on code in Apache Tomcat.
*
* @author Remy Maucherat
* @author Andrey Grebnev
@@ -46,7 +47,7 @@ public class FastHttpDateFormat {
new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)
};
/** GMT timezone - all HTTP dates are on GMT */
/** GMT time zone - all HTTP dates are on GMT */
protected static final TimeZone gmtZone = TimeZone.getTimeZone("GMT");
static {
@@ -64,10 +65,10 @@ public class FastHttpDateFormat {
protected static String currentDate = null;
/** Formatter cache. */
protected static final HashMap formatCache = new HashMap();
protected static final HashMap<Long,String> formatCache = new HashMap<Long,String>();
/** Parser cache. */
protected static final HashMap parseCache = new HashMap();
protected static final HashMap<String,Long> parseCache = new HashMap<String,Long>();
//~ Methods ========================================================================================================
@@ -84,7 +85,7 @@ public class FastHttpDateFormat {
Long longValue = new Long(value);
try {
cachedDate = (String) formatCache.get(longValue);
cachedDate = formatCache.get(longValue);
} catch (Exception e) {}
if (cachedDate != null) {
@@ -163,7 +164,7 @@ public class FastHttpDateFormat {
* @param value The string to parse
* @param threadLocalformats Array of formats to use for parsing. If <code>null</code>, HTTP formats are used.
*
* @return Parsed date (or -1 if error occured)
* @return Parsed date (or -1 if error occurred)
*/
public static final long parseDate(String value, DateFormat[] threadLocalformats) {
Long cachedDate = null;
@@ -205,6 +206,7 @@ public class FastHttpDateFormat {
* @param key Key to be updated
* @param value New value
*/
@SuppressWarnings("unchecked")
private static void updateCache(HashMap cache, Object key, Object value) {
if (value == null) {
return;
@@ -12,13 +12,13 @@ import org.springframework.security.Authentication;
*/
public interface AuthenticationUserDetailsService {
/**
*
* @param token The pre-authenticated authentication token
* @return UserDetails for the given authentication token, never null.
* @throws UsernameNotFoundException
* if no user details can be found for the given authentication
* token
*/
UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException;
/**
*
* @param token The pre-authenticated authentication token
* @return UserDetails for the given authentication token, never null.
* @throws UsernameNotFoundException
* if no user details can be found for the given authentication
* token
*/
UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException;
}
@@ -14,33 +14,33 @@ import org.springframework.util.Assert;
* @since 2.0
*/
public class UserDetailsByNameServiceWrapper implements AuthenticationUserDetailsService, InitializingBean {
private UserDetailsService userDetailsService = null;
private UserDetailsService userDetailsService = null;
/**
* Check whether all required properties have been set.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "UserDetailsService must be set");
}
/**
* Check whether all required properties have been set.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "UserDetailsService must be set");
}
/**
* Get the UserDetails object from the wrapped UserDetailsService
* implementation
*/
public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException,
DataAccessException {
return userDetailsService.loadUserByUsername(authentication.getName());
}
/**
* Get the UserDetails object from the wrapped UserDetailsService
* implementation
*/
public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException,
DataAccessException {
return userDetailsService.loadUserByUsername(authentication.getName());
}
/**
* Set the wrapped UserDetailsService implementation
*
* @param aUserDetailsService
* The wrapped UserDetailsService to set
*/
public void setUserDetailsService(UserDetailsService aUserDetailsService) {
userDetailsService = aUserDetailsService;
}
/**
* Set the wrapped UserDetailsService implementation
*
* @param aUserDetailsService
* The wrapped UserDetailsService to set
*/
public void setUserDetailsService(UserDetailsService aUserDetailsService) {
userDetailsService = aUserDetailsService;
}
}
@@ -186,6 +186,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
* Executes the SQL <tt>usersByUsernameQuery</tt> and returns a list of UserDetails objects.
* There should normally only be one matching user.
*/
@SuppressWarnings("unchecked")
protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(usersByUsernameQuery, new String[] {username}, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
@@ -203,6 +204,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
*
* @return a list of GrantedAuthority objects for the user
*/
@SuppressWarnings("unchecked")
protected List<GrantedAuthority> loadUserAuthorities(String username) {
return getJdbcTemplate().query(authoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
@@ -219,6 +221,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
*
* @return a list of GrantedAuthority objects for the user
*/
@SuppressWarnings("unchecked")
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
@@ -189,7 +189,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
String username = currentUser.getName();
// If an authentication manager has been set, reauthenticate the user with the supplied password.
// If an authentication manager has been set, re-authenticate the user with the supplied password.
if (authenticationManager != null) {
logger.debug("Reauthenticating user '"+ username + "' for password change request.");
@@ -200,7 +200,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
logger.debug("Changing password for user '"+ username + "'");
getJdbcTemplate().update(changePasswordSql, new String[] {newPassword, username});
getJdbcTemplate().update(changePasswordSql, newPassword, username);
SecurityContextHolder.getContext().setAuthentication(createNewAuthentication(currentUser, newPassword));
@@ -218,7 +218,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
}
public boolean userExists(String username) {
List users = getJdbcTemplate().queryForList(userExistsSql, new Object[] {username});
List<String> users = getJdbcTemplate().queryForList(userExistsSql, new String[] {username}, String.class);
if (users.size() > 1) {
throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'", 1);
@@ -245,7 +245,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
logger.debug("Creating new group '" + groupName + "' with authorities " +
AuthorityUtils.authorityListToSet(authorities));
getJdbcTemplate().update(insertGroupSql, new String[] {groupName});
getJdbcTemplate().update(insertGroupSql, new Object[] {groupName});
final int groupId = findGroupId(groupName);
@@ -280,7 +280,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.hasText(oldName);
Assert.hasText(newName);
getJdbcTemplate().update(renameGroupSql, new String[] {newName, oldName});
getJdbcTemplate().update(renameGroupSql, new Object[] {newName, oldName});
}
public void addUserToGroup(final String username, final String groupName) {
@@ -316,6 +316,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
userCache.removeUserFromCache(username);
}
@SuppressWarnings("unchecked")
public List<GrantedAuthority> findGroupAuthorities(String groupName) {
logger.debug("Loading authorities for group '" + groupName + "'");
Assert.hasText(groupName);
@@ -29,19 +29,19 @@ import org.springframework.ldap.core.DirContextOperations;
* @version $Id$
*/
public class InetOrgPerson extends Person {
private String carLicense;
// Person.cn
private String carLicense;
// Person.cn
private String destinationIndicator;
private String departmentNumber;
// Person.description
private String displayName;
private String employeeNumber;
private String homePhone;
private String homePostalAddress;
private String initials;
private String mail;
private String mobile;
private String o;
private String departmentNumber;
// Person.description
private String displayName;
private String employeeNumber;
private String homePhone;
private String homePostalAddress;
private String initials;
private String mail;
private String mobile;
private String o;
private String ou;
private String postalAddress;
private String postalCode;
@@ -49,7 +49,7 @@ public class InetOrgPerson extends Person {
private String street;
// Person.sn
// Person.telephoneNumber
private String title;
private String title;
private String uid;
public String getUid() {
@@ -65,7 +65,7 @@ public class InetOrgPerson extends Person {
}
public String getInitials() {
return initials;
return initials;
}
public String getDestinationIndicator() {
@@ -73,58 +73,58 @@ public class InetOrgPerson extends Person {
}
public String getO() {
return o;
}
return o;
}
public String getOu() {
return ou;
}
return ou;
}
public String getTitle() {
return title;
}
public String getTitle() {
return title;
}
public String getCarLicense() {
return carLicense;
}
public String getCarLicense() {
return carLicense;
}
public String getDepartmentNumber() {
return departmentNumber;
}
public String getDepartmentNumber() {
return departmentNumber;
}
public String getDisplayName() {
return displayName;
}
public String getHomePhone() {
return homePhone;
}
public String getRoomNumber() {
return roomNumber;
}
public String getDisplayName() {
return displayName;
}
public String getHomePhone() {
return homePhone;
}
public String getRoomNumber() {
return roomNumber;
}
public String getHomePostalAddress() {
return homePostalAddress;
}
public String getHomePostalAddress() {
return homePostalAddress;
}
public String getMobile() {
return mobile;
}
public String getMobile() {
return mobile;
}
public String getPostalAddress() {
return postalAddress;
}
public String getPostalAddress() {
return postalAddress;
}
public String getPostalCode() {
return postalCode;
}
public String getPostalCode() {
return postalCode;
}
public String getStreet() {
return street;
}
public String getStreet() {
return street;
}
protected void populateContext(DirContextAdapter adapter) {
protected void populateContext(DirContextAdapter adapter) {
super.populateContext(adapter);
adapter.setAttributeValue("carLicense", carLicense);
adapter.setAttributeValue("departmentNumber", departmentNumber);
@@ -172,7 +172,7 @@ public class InetOrgPerson extends Person {
setUid(copyMe.getUid());
}
public Essence(DirContextOperations ctx) {
public Essence(DirContextOperations ctx) {
super(ctx);
setCarLicense(ctx.getStringAttribute("carLicense"));
setDepartmentNumber(ctx.getStringAttribute("departmentNumber"));
@@ -235,8 +235,8 @@ public class InetOrgPerson extends Person {
}
public void setDepartmentNumber(String departmentNumber) {
((InetOrgPerson) instance).departmentNumber = departmentNumber;
}
((InetOrgPerson) instance).departmentNumber = departmentNumber;
}
public void setDisplayName(String displayName) {
((InetOrgPerson) instance).displayName = displayName;
@@ -255,23 +255,23 @@ public class InetOrgPerson extends Person {
}
public void setStreet(String street) {
((InetOrgPerson) instance).street = street;
}
((InetOrgPerson) instance).street = street;
}
public void setPostalCode(String postalCode) {
((InetOrgPerson) instance).postalCode = postalCode;
}
((InetOrgPerson) instance).postalCode = postalCode;
}
public void setPostalAddress(String postalAddress) {
((InetOrgPerson) instance).postalAddress = postalAddress;
}
((InetOrgPerson) instance).postalAddress = postalAddress;
}
public void setMobile(String mobile) {
((InetOrgPerson) instance).mobile = mobile;
}
((InetOrgPerson) instance).mobile = mobile;
}
public void setHomePostalAddress(String homePostalAddress) {
((InetOrgPerson) instance).homePostalAddress = homePostalAddress;
}
((InetOrgPerson) instance).homePostalAddress = homePostalAddress;
}
}
}
@@ -49,6 +49,7 @@ import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import java.util.Arrays;
import java.util.LinkedList;
@@ -107,7 +108,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
public Object mapFromAttributes(Attributes attributes) throws NamingException {
Attribute roleAttr = attributes.get(groupRoleAttributeName);
NamingEnumeration ne = roleAttr.getAll();
NamingEnumeration<?> ne = roleAttr.getAll();
// assert ne.hasMore();
Object group = ne.next();
String role = group.toString();
@@ -204,9 +205,10 @@ public class LdapUserDetailsManager implements UserDetailsManager {
* @param username the user whose roles are required.
* @return the granted authorities returned by the group search
*/
@SuppressWarnings("unchecked")
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
SearchExecutor se = new SearchExecutor() {
public NamingEnumeration executeSearch(DirContext ctx) throws NamingException {
public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) throws NamingException {
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] {groupRoleAttributeName});
@@ -257,9 +259,9 @@ public class LdapUserDetailsManager implements UserDetailsManager {
copyToContext(user, ctx);
// Remove the objectclass attribute from the list of mods (if present).
List mods = new LinkedList(Arrays.asList(ctx.getModificationItems()));
List<ModificationItem> mods = new LinkedList<ModificationItem>(Arrays.asList(ctx.getModificationItems()));
ListIterator<ModificationItem> modIt = mods.listIterator();
ListIterator modIt = mods.listIterator();
while(modIt.hasNext()) {
ModificationItem mod = (ModificationItem) modIt.next();
Attribute a = mod.getAttribute();
@@ -268,7 +270,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
}
}
template.modifyAttributes(dn, (ModificationItem[]) mods.toArray(new ModificationItem[mods.size()]));
template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()]));
// template.rebind(dn, ctx, null);
// Remove the old authorities and replace them with the new one
@@ -38,7 +38,7 @@ public class UserMap {
//~ Instance fields ================================================================================================
private Map userMap = new HashMap();
private Map<String, UserDetails> userMap = new HashMap<String, UserDetails>();
//~ Methods ========================================================================================================
@@ -66,7 +66,7 @@ public class UserMap {
* @throws UsernameNotFoundException if the user could not be found
*/
public UserDetails getUser(String username) throws UsernameNotFoundException {
UserDetails result = (UserDetails) this.userMap.get(username.toLowerCase());
UserDetails result = this.userMap.get(username.toLowerCase());
if (result == null) {
throw new UsernameNotFoundException("Could not find user: " + username, username);
@@ -90,7 +90,7 @@ public class UserMap {
* @param users {@link Map} &lt;{@link String}, {@link UserDetails}> with pairs (username, userdetails)
* @since 1.1
*/
public void setUsers(Map users) {
public void setUsers(Map<String, UserDetails> users) {
this.userMap = users;
}
}
@@ -49,7 +49,7 @@ public class UserMapEditor extends PropertyEditorSupport {
// Now we have properties, process each one individually
UserAttributeEditor configAttribEd = new UserAttributeEditor();
for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
for (Iterator<?> iter = props.keySet().iterator(); iter.hasNext();) {
String username = (String) iter.next();
String value = props.getProperty(username);
@@ -36,7 +36,7 @@ public final class FieldUtils {
//~ Methods ========================================================================================================
public static String getAccessorName(String fieldName, Class type) {
public static String getAccessorName(String fieldName, Class<?> type) {
Assert.hasText(fieldName, "FieldName required");
Assert.notNull(type, "Type required");
@@ -57,7 +57,7 @@ public final class FieldUtils {
*
* @throws IllegalStateException if field could not be found
*/
public static Field getField(Class clazz, String fieldName) throws IllegalStateException {
public static Field getField(Class<?> clazz, String fieldName) throws IllegalStateException {
Assert.notNull(clazz, "Class required");
Assert.hasText(fieldName, "Field name required");
@@ -72,7 +72,7 @@ public final class FieldUtils {
throw new IllegalStateException("Could not locate field '" + fieldName + "' on class " + clazz);
}
}
/**
* Returns the value of a (nested) field on a bean. Intended for testing.
* @param bean the object
@@ -80,22 +80,22 @@ public final class FieldUtils {
* @return the value of the nested field
*/
public static Object getFieldValue(Object bean, String fieldName) throws IllegalAccessException {
Assert.notNull(bean, "Bean cannot be null");
Assert.hasText(fieldName, "Field name required");
Assert.notNull(bean, "Bean cannot be null");
Assert.hasText(fieldName, "Field name required");
String[] nestedFields = StringUtils.tokenizeToStringArray(fieldName, ".");
Class componentClass = bean.getClass();
Class<?> componentClass = bean.getClass();
Field field = null;
Object value = bean;
for (int i=0; i < nestedFields.length; i++) {
field = getField(componentClass, nestedFields[i]);
field.setAccessible(true);
value = field.get(value);
value = field.get(value);
componentClass = value.getClass();
}
return value;
}
public static String getMutatorName(String fieldName) {
@@ -26,7 +26,7 @@ public abstract class RedirectUtils {
* @param response the response to redirect
* @param url the target url to redirect to
* @param useRelativeContext if true, causes any redirection URLs to be calculated minus the protocol
* and context path.
* and context path.
*
* @see AbstractProcessingFilter#setUseRelativeContext(boolean)
*/
@@ -34,29 +34,29 @@ public abstract class RedirectUtils {
HttpServletResponse response,
String url,
boolean useRelativeContext) throws IOException {
String finalUrl;
if (!url.startsWith("http://") && !url.startsWith("https://")) {
if (useRelativeContext) {
finalUrl = url;
}
else {
finalUrl = request.getContextPath() + url;
}
}
String finalUrl;
if (!url.startsWith("http://") && !url.startsWith("https://")) {
if (useRelativeContext) {
finalUrl = url;
}
else {
finalUrl = request.getContextPath() + url;
}
}
else if (useRelativeContext) {
// Calculate the relative URL from the fully qualifed URL, minus the protocol and base context.
int len = request.getContextPath().length();
int index = url.indexOf(request.getContextPath()) + len;
finalUrl = url.substring(index);
// Calculate the relative URL from the fully qualifed URL, minus the protocol and base context.
int len = request.getContextPath().length();
int index = url.indexOf(request.getContextPath()) + len;
finalUrl = url.substring(index);
if (finalUrl.length() > 1 && finalUrl.charAt(0) == '/') {
finalUrl = finalUrl.substring(1);
}
}
else {
finalUrl = url;
}
finalUrl = finalUrl.substring(1);
}
}
else {
finalUrl = url;
}
response.sendRedirect(response.encodeRedirectURL(finalUrl));
response.sendRedirect(response.encodeRedirectURL(finalUrl));
}
}
@@ -1,8 +1,5 @@
package org.springframework.security.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.regex.Pattern;
/**
@@ -10,8 +7,6 @@ import java.util.regex.Pattern;
* @version $Id$
*/
public class RegexUrlPathMatcher implements UrlMatcher {
private static final Log logger = LogFactory.getLog(RegexUrlPathMatcher.class);
private boolean requiresLowerCaseUrl = false;
public Object compile(String path) {
@@ -2,7 +2,6 @@ package org.springframework.security.util;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
@@ -21,28 +20,29 @@ import org.springframework.security.context.SecurityContextHolder;
*/
public final class SessionUtils {
private final static Log logger = LogFactory.getLog(SessionUtils.class);
SessionUtils() {}
public static void startNewSessionIfRequired(HttpServletRequest request, boolean migrateAttributes,
@SuppressWarnings("unchecked")
public static void startNewSessionIfRequired(HttpServletRequest request, boolean migrateAttributes,
SessionRegistry sessionRegistry) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
String originalSessionId = session.getId();
if (logger.isDebugEnabled()) {
logger.debug("Invalidating session with Id '" + originalSessionId +"' " + (migrateAttributes ? "and" : "without") + " migrating attributes.");
}
}
HashMap<String, Object> attributesToMigrate = null;
HashMap attributesToMigrate = null;
if (migrateAttributes) {
attributesToMigrate = new HashMap();
attributesToMigrate = new HashMap<String, Object>();
Enumeration enumer = session.getAttributeNames();
@@ -51,29 +51,26 @@ public final class SessionUtils {
attributesToMigrate.put(key, session.getAttribute(key));
}
}
session.invalidate();
session = request.getSession(true); // we now have a new session
if (logger.isDebugEnabled()) {
logger.debug("Started new session: " + session.getId());
}
if (attributesToMigrate != null) {
Iterator iter = attributesToMigrate.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
session.setAttribute((String) entry.getKey(), entry.getValue());
if (attributesToMigrate != null) {
for (Map.Entry<String, Object> entry : attributesToMigrate.entrySet()) {
session.setAttribute(entry.getKey(), entry.getValue());
}
}
if (sessionRegistry != null) {
sessionRegistry.removeSessionInformation(originalSessionId);
Object principal = SessionRegistryUtils.obtainPrincipalFromAuthentication(
SecurityContextHolder.getContext().getAuthentication());
sessionRegistry.registerNewSession(session.getId(), principal);
}
}
}
}
@@ -127,7 +127,8 @@ public class ThrowableAnalyzer {
*
* @return the types for which extractors are registered
*/
final Class[] getRegisteredTypes() {
@SuppressWarnings("unchecked")
final Class<? extends Throwable>[] getRegisteredTypes() {
Set<Class<? extends Throwable>> typeList = this.extractorMap.keySet();
return typeList.toArray(new Class[typeList.size()]);
}
@@ -168,6 +168,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW
}
@Override
@SuppressWarnings("unchecked")
public Enumeration getHeaderNames() {
if (savedRequest == null) {
return super.getHeaderNames();
@@ -177,6 +178,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW
}
@Override
@SuppressWarnings("unchecked")
public Enumeration getHeaders(String name) {
if (savedRequest == null) {
return super.getHeaders(name);
@@ -223,6 +225,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW
}
@Override
@SuppressWarnings("unchecked")
public Enumeration getLocales() {
if (savedRequest == null) {
return super.getLocales();
@@ -278,6 +281,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW
}
@Override
@SuppressWarnings("unchecked")
public Map getParameterMap() {
if (savedRequest == null) {
return super.getParameterMap();
@@ -293,6 +297,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW
return parameterMap;
}
@SuppressWarnings("unchecked")
private Set<String> getCombinedParameterNames() {
Set<String> names = new HashSet<String>();
names.addAll(super.getParameterMap().keySet());
@@ -305,6 +310,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW
}
@Override
@SuppressWarnings("unchecked")
public Enumeration getParameterNames() {
return new Enumerator(getCombinedParameterNames());
}
@@ -20,6 +20,7 @@ import junit.framework.TestCase;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken;
import org.springframework.security.providers.rememberme.RememberMeAuthenticationToken;
import org.springframework.security.util.AuthorityUtils;
/**
@@ -35,21 +36,17 @@ public class AuthenticationTrustResolverImplTests extends TestCase {
public void testCorrectOperationIsAnonymous() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertTrue(trustResolver.isAnonymous(
new AnonymousAuthenticationToken("ignored", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")})));
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))));
assertFalse(trustResolver.isAnonymous(
new TestingAuthenticationToken("ignored", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")})));
new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))));
}
public void testCorrectOperationIsRememberMe() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertTrue(trustResolver.isRememberMe(
new RememberMeAuthenticationToken("ignored", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")})));
new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))));
assertFalse(trustResolver.isAnonymous(
new TestingAuthenticationToken("ignored", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")})));
new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))));
}
public void testGettersSetters() {
@@ -27,8 +27,8 @@ import org.junit.Test;
* @version $Id$
*/
public class GrantedAuthorityImplTests {
@Test
@Test
public void equalsBehavesAsExpected() throws Exception {
GrantedAuthorityImpl auth1 = new GrantedAuthorityImpl("TEST");
GrantedAuthorityImpl auth2 = new GrantedAuthorityImpl("TEST");
@@ -53,28 +53,28 @@ public class GrantedAuthorityImplTests {
assertTrue(!auth1.equals(int1));
}
@Test
@Test
public void toStringReturnsAuthorityValue() {
GrantedAuthorityImpl auth = new GrantedAuthorityImpl("TEST");
assertEquals("TEST", auth.toString());
}
@Test
public void compareToGrantedAuthorityWithSameValueReturns0() {
assertEquals(0, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority("TEST")));
}
@Test
public void compareToGrantedAuthorityWithSameValueReturns0() {
assertEquals(0, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority("TEST")));
}
@Test
public void compareToNullReturnsNegativeOne() {
assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(null));
}
/* SEC-899 */
@Test
public void compareToHandlesCustomAuthorityWhichReturnsNullFromGetAuthority() {
assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority()));
}
@Test
public void compareToNullReturnsNegativeOne() {
assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(null));
}
/* SEC-899 */
@Test
public void compareToHandlesCustomAuthorityWhichReturnsNullFromGetAuthority() {
assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority()));
}
//~ Inner Classes ==================================================================================================
private class MockGrantedAuthority implements GrantedAuthority {
@@ -88,8 +88,8 @@ public class GrantedAuthorityImplTests {
}
public int compareTo(Object o) {
throw new UnsupportedOperationException();
}
throw new UnsupportedOperationException();
}
public String getAuthority() {
return this.role;
@@ -1,39 +0,0 @@
/* Copyright 2004, 2005, 2006 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 org.springframework.security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Mocks a <code>FilterChain</code> but with no behaviour.
*
* @author Ben Alex
* @version $Id$
*/
public class MockFilterChain implements FilterChain {
//~ Methods ========================================================================================================
public void doFilter(ServletRequest arg0, ServletResponse arg1)
throws IOException, ServletException {
throw new UnsupportedOperationException("mock method not implemented");
}
}
@@ -28,9 +28,9 @@ import javax.servlet.ServletContext;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class MockFilterConfig implements FilterConfig {
//~ Instance fields ================================================================================================
private Map map = new HashMap();
//~ Methods ========================================================================================================
@@ -29,6 +29,7 @@ import java.lang.reflect.Method;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("unchecked")
public class MockJoinPoint implements JoinPoint {
//~ Instance fields ================================================================================================
@@ -30,28 +30,28 @@ public class SecurityConfigTests {
//~ Methods ========================================================================================================
@Test
@Test
public void testHashCode() {
SecurityConfig config = new SecurityConfig("TEST");
Assert.assertEquals("TEST".hashCode(), config.hashCode());
}
@Test(expected=IllegalArgumentException.class)
public void testCannotConstructWithNullAttribute() {
new SecurityConfig(null); // SEC-727
public void testCannotConstructWithNullAttribute() {
new SecurityConfig(null); // SEC-727
}
@Test(expected=IllegalArgumentException.class)
public void testCannotConstructWithEmptyAttribute() {
new SecurityConfig(""); // SEC-727
public void testCannotConstructWithEmptyAttribute() {
new SecurityConfig(""); // SEC-727
}
@Test(expected=NoSuchMethodException.class)
public void testNoArgConstructorDoesntExist() throws Exception {
SecurityConfig.class.getDeclaredConstructor((Class[]) null);
SecurityConfig.class.getDeclaredConstructor((Class[]) null);
}
@Test
@Test
public void testObjectEquals() throws Exception {
SecurityConfig security1 = new SecurityConfig("TEST");
SecurityConfig security2 = new SecurityConfig("TEST");
@@ -77,12 +77,12 @@ public class SecurityConfigTests {
Assert.assertTrue(!security1.equals(int1));
}
@Test
@Test
public void testToString() {
SecurityConfig config = new SecurityConfig("TEST");
Assert.assertEquals("TEST", config.toString());
}
}
//~ Inner Classes ==================================================================================================
private class MockConfigAttribute implements ConfigAttribute {
@@ -7,5 +7,5 @@ package org.springframework.security.annotation;
*
*/
public class Entity {
public Entity(String someParameter) {}
public Entity(String someParameter) {}
}
@@ -14,6 +14,7 @@ import junit.framework.TestCase;
* @author TSARDD
* @since 18-okt-2007
*/
@SuppressWarnings("unchecked")
public class XmlMappableRolesRetrieverTests extends TestCase {
private static final String DEFAULT_XML = "<roles><role>Role1</role><role>Role2</role></roles>";
@@ -23,8 +23,8 @@ public class CustomAuthenticationProviderBeanDefinitionDecoratorTests {
ProviderManager authMgr = (ProviderManager) ctx.getBean(BeanIds.AUTHENTICATION_MANAGER);
assertEquals(1, authMgr.getProviders().size());
}
@Test
public void decoratedBeanAndRegisteredProviderAreTheSameObject() {
InMemoryXmlApplicationContext ctx = new InMemoryXmlApplicationContext(
@@ -191,6 +191,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// Expression configuration tests
@SuppressWarnings("unchecked")
@Test
public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception {
setContext("<global-method-security expression-annotations='enabled'/>" + AUTH_PROVIDER_XML);
@@ -1,15 +1,16 @@
package org.springframework.security.config;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.AuthenticationCredentialsNotFoundException;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.AuthenticationCredentialsNotFoundException;
import org.springframework.security.AccessDeniedException;
import static org.junit.Assert.*;
import org.junit.*;
import org.springframework.security.util.AuthorityUtils;
/**
* @author Luke Taylor
@@ -51,7 +52,7 @@ public class InterceptMethodsBeanDefinitionDecoratorTests {
@Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")});
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
@@ -61,7 +62,7 @@ public class InterceptMethodsBeanDefinitionDecoratorTests {
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")});
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
try {
@@ -5,11 +5,10 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.AuthenticationCredentialsNotFoundException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.annotation.BusinessService;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.security.util.InMemoryXmlApplicationContext;
/**
@@ -46,7 +45,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
@Test
public void permitAllShouldBeDefaultAttribute() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")});
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someOther(0);
@@ -55,7 +54,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
@Test
public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")});
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someUserMethod1();
@@ -64,7 +63,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
@Test(expected=AccessDeniedException.class)
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")});
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someAdminMethod();
@@ -41,7 +41,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
Set authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertEquals(3, authorities.size());
assertTrue(authorities.contains("ROLE_DEVELOPERS"));
}
@@ -66,20 +66,20 @@ public class LdapUserServiceBeanDefinitionParserTests {
" user-search-filter='(uid={0})' " +
" group-search-filter='member={0}' role-prefix='PREFIX_'/>" +
"<ldap-user-service id='ldapUDSNoPrefix' " +
" user-search-filter='(uid={0})' " +
" group-search-filter='member={0}' role-prefix='none'/><ldap-server />");
" user-search-filter='(uid={0})' " +
" group-search-filter='member={0}' role-prefix='none'/><ldap-server />");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("PREFIX_DEVELOPERS"));
uds = (UserDetailsService) appCtx.getBean("ldapUDSNoPrefix");
ben = uds.loadUserByUsername("ben");
assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("DEVELOPERS"));
assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("DEVELOPERS"));
}
@Test
public void differentGroupRoleAttributeWorksAsExpected() throws Exception {
setContext("<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' group-role-attribute='ou' group-search-filter='member={0}' /><ldap-server />");
@@ -87,12 +87,12 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
Set authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertEquals(3, authorities.size());
assertTrue(authorities.contains(new GrantedAuthorityImpl("ROLE_DEVELOPER")));
}
@Test
public void isSupportedByAuthenticationProviderElement() {
setContext(
@@ -101,7 +101,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
" <ldap-user-service user-search-filter='(uid={0})' />" +
"</authentication-provider>");
}
@Test
public void personContextMapperIsSupported() {
setContext(
@@ -111,7 +111,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(ben instanceof Person);
}
@Test
public void inetOrgContextMapperIsSupported() {
setContext(
@@ -121,8 +121,8 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(ben instanceof InetOrgPerson);
}
private void setContext(String context) {
appCtx = new InMemoryXmlApplicationContext(context);
}
@@ -11,15 +11,15 @@ import org.springframework.beans.factory.config.BeanPostProcessor;
*/
public class MockUserServiceBeanPostProcessor implements BeanPostProcessor {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof PostProcessedMockUserDetailsService) {
((PostProcessedMockUserDetailsService)bean).setPostProcessorWasHere("Hello from the post processor!");
}
return bean;
}
return bean;
}
}
@@ -6,22 +6,22 @@ import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
public class PostProcessedMockUserDetailsService implements UserDetailsService {
private String postProcessorWasHere;
private String postProcessorWasHere;
public PostProcessedMockUserDetailsService() {
public PostProcessedMockUserDetailsService() {
this.postProcessorWasHere = "Post processor hasn't been yet";
}
public String getPostProcessorWasHere() {
return postProcessorWasHere;
}
return postProcessorWasHere;
}
public void setPostProcessorWasHere(String postProcessorWasHere) {
this.postProcessorWasHere = postProcessorWasHere;
}
public void setPostProcessorWasHere(String postProcessorWasHere) {
this.postProcessorWasHere = postProcessorWasHere;
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
throw new UnsupportedOperationException("Not for actual use");
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
throw new UnsupportedOperationException("Not for actual use");
}
}
@@ -40,6 +40,7 @@ import javax.servlet.ServletResponse;
* @author Ben Alex
* @version $Id$
*/
@SuppressWarnings("deprecation")
public class HttpSessionContextIntegrationFilterTests extends TestCase {
// Build an Authentication object we simulate came from HttpSession
private UsernamePasswordAuthenticationToken sessionPrincipal = new UsernamePasswordAuthenticationToken(
@@ -40,19 +40,9 @@ import java.util.Map;
* @version $Id$
*/
public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCase {
//~ Constructors ===================================================================================================
public AuthenticationSimpleHttpInvokerRequestExecutorTests() {
super();
}
public AuthenticationSimpleHttpInvokerRequestExecutorTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.clearContext();
@@ -91,7 +81,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas
//~ Inner Classes ==================================================================================================
private class MockHttpURLConnection extends HttpURLConnection {
private Map requestProperties = new HashMap();
private Map<String,String> requestProperties = new HashMap<String,String>();
public MockHttpURLConnection(URL u) {
super(u);
@@ -106,7 +96,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas
}
public String getRequestProperty(String key) {
return (String) requestProperties.get(key);
return requestProperties.get(key);
}
public void setRequestProperty(String key, String value) {
@@ -47,7 +47,7 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
}
private ContextPropagatingRemoteInvocation getRemoteInvocation() throws Exception {
Class clazz = TargetObject.class;
Class<TargetObject> clazz = TargetObject.class;
Method method = clazz.getMethod("makeLowerCase", new Class[] {String.class});
MethodInvocation mi = new SimpleMethodInvocation(new TargetObject(), method, "SOME_STRING");
@@ -67,7 +67,7 @@ public class AuthenticationEventTests extends TestCase {
AuthenticationException exception = new DisabledException("TEST");
try {
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(null, exception);
new AuthenticationFailureDisabledEvent(null, exception);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -116,40 +116,40 @@ public class ExpressionAnnotationMethodDefinitionSourceTests {
//~ Inner Classes ==================================================================================================
public static interface ReturnVoid {
public void doSomething(List param);
public void doSomething(List<?> param);
}
public static interface ReturnAList {
public List doSomething(List param);
public List<?> doSomething(List<?> param);
}
@PreAuthorize("interfaceAuthzExpression")
public static interface ReturnAnotherList {
@PreAuthorize("interfaceMethodAuthzExpression")
@PreFilter(filterTarget="param", value="interfacePreFilterExpression")
public List doSomething(List param);
public List<?> doSomething(List<?> param);
}
@PreAuthorize("someExpression")
public static class ReturnVoidImpl1 implements ReturnVoid {
public void doSomething(List param) {}
public void doSomething(List<?> param) {}
}
@PreAuthorize("someExpression")
public static class ReturnVoidImpl2 implements ReturnVoid {
@PreFilter(filterTarget="param", value="somePreFilterExpression")
public void doSomething(List param) {}
public void doSomething(List<?> param) {}
}
public static class ReturnVoidImpl3 implements ReturnVoid {
@PreFilter(filterTarget="param", value="somePreFilterExpression")
public void doSomething(List param) {}
public void doSomething(List<?> param) {}
}
public static class ReturnAListImpl1 implements ReturnAList {
@PostFilter("somePostFilterExpression")
public List doSomething(List param) {return param;}
public List<?> doSomething(List<?> param) {return param;}
}
public static class ReturnAListImpl2 implements ReturnAList {
@@ -157,16 +157,16 @@ public class ExpressionAnnotationMethodDefinitionSourceTests {
@PreFilter(filterTarget="param", value="somePreFilterExpression")
@PostFilter("somePostFilterExpression")
@PostAuthorize("somePostAuthorizeExpression")
public List doSomething(List param) {return param;}
public List<?> doSomething(List<?> param) {return param;}
}
public static class ReturnAnotherListImpl1 implements ReturnAnotherList {
public List doSomething(List param) {return param;}
public List<?> doSomething(List<?> param) {return param;}
}
public static class ReturnAnotherListImpl2 implements ReturnAnotherList {
@PreFilter(filterTarget="param", value="classMethodPreFilterExpression")
public List doSomething(List param) {return param;}
public List<?> doSomething(List<?> param) {return param;}
}
}

Some files were not shown because too many files have changed in this diff Show More