Anonymous type can be replaced with lambda

This commit is contained in:
Lars Grefer 2019-08-06 23:40:48 +02:00 committed by Josh Cummings
parent 05f42a4995
commit fb39d9c255
53 changed files with 347 additions and 722 deletions

View File

@ -17,7 +17,6 @@ package org.springframework.security.acls.jdbc;
import java.io.Serializable; import java.io.Serializable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -33,7 +32,6 @@ import javax.sql.DataSource;
import org.springframework.core.convert.ConversionException; import org.springframework.core.convert.ConversionException;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.security.acls.domain.AccessControlEntryImpl; import org.springframework.security.acls.domain.AccessControlEntryImpl;
import org.springframework.security.acls.domain.AclAuthorizationStrategy; import org.springframework.security.acls.domain.AclAuthorizationStrategy;
@ -248,14 +246,12 @@ public class BasicLookupStrategy implements LookupStrategy {
String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size()); String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size());
Set<Long> parentsToLookup = jdbcTemplate.query(sql, Set<Long> parentsToLookup = jdbcTemplate.query(sql,
new PreparedStatementSetter() { ps -> {
public void setValues(PreparedStatement ps) throws SQLException { int i = 0;
int i = 0;
for (Long toFind : findNow) { for (Long toFind : findNow) {
i++; i++;
ps.setLong(i, toFind); ps.setLong(i, toFind);
}
} }
}, new ProcessResultSet(acls, sids)); }, new ProcessResultSet(acls, sids));
@ -383,22 +379,20 @@ public class BasicLookupStrategy implements LookupStrategy {
objectIdentities.size()); objectIdentities.size());
Set<Long> parentsToLookup = jdbcTemplate.query(sql, Set<Long> parentsToLookup = jdbcTemplate.query(sql,
new PreparedStatementSetter() { ps -> {
public void setValues(PreparedStatement ps) throws SQLException { int i = 0;
int i = 0; for (ObjectIdentity oid : objectIdentities) {
for (ObjectIdentity oid : objectIdentities) { // Determine prepared statement values for this iteration
// Determine prepared statement values for this iteration String type = oid.getType();
String type = oid.getType();
// No need to check for nulls, as guaranteed non-null by // No need to check for nulls, as guaranteed non-null by
// ObjectIdentity.getIdentifier() interface contract // ObjectIdentity.getIdentifier() interface contract
String identifier = oid.getIdentifier().toString(); String identifier = oid.getIdentifier().toString();
// Inject values // Inject values
ps.setString((2 * i) + 1, identifier); ps.setString((2 * i) + 1, identifier);
ps.setString((2 * i) + 2, type); ps.setString((2 * i) + 2, type);
i++; i++;
}
} }
}, new ProcessResultSet(acls, sids)); }, new ProcessResultSet(acls, sids));

View File

@ -16,8 +16,6 @@
package org.springframework.security.acls.jdbc; package org.springframework.security.acls.jdbc;
import java.io.Serializable; import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -29,7 +27,6 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.AclService;
@ -95,14 +92,11 @@ public class JdbcAclService implements AclService {
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) { public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() }; Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() };
List<ObjectIdentity> objects = jdbcOperations.query(findChildrenSql, args, List<ObjectIdentity> objects = jdbcOperations.query(findChildrenSql, args,
new RowMapper<ObjectIdentity>() { (rs, rowNum) -> {
public ObjectIdentity mapRow(ResultSet rs, int rowNum) String javaType = rs.getString("class");
throws SQLException { Serializable identifier = (Serializable) rs.getObject("obj_id");
String javaType = rs.getString("class"); identifier = aclClassIdUtils.identifierFrom(identifier, rs);
Serializable identifier = (Serializable) rs.getObject("obj_id"); return new ObjectIdentityImpl(javaType, identifier);
identifier = aclClassIdUtils.identifierFrom(identifier, rs);
return new ObjectIdentityImpl(javaType, identifier);
}
}); });
if (objects.size() == 0) { if (objects.size() == 0) {

View File

@ -72,11 +72,7 @@ public aspect AnnotationSecurityAspect implements InitializingBean {
return proceed(); return proceed();
} }
AspectJCallback callback = new AspectJCallback() { AspectJCallback callback = () -> proceed();
public Object proceedWithObject() {
return proceed();
}
};
return this.securityInterceptor.invoke(thisJoinPoint, callback); return this.securityInterceptor.invoke(thisJoinPoint, callback);
} }

View File

@ -67,11 +67,7 @@ public class CasAuthenticationFilterTests {
request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ"); request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ");
CasAuthenticationFilter filter = new CasAuthenticationFilter(); CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager(new AuthenticationManager() { filter.setAuthenticationManager(a -> a);
public Authentication authenticate(Authentication a) {
return a;
}
});
assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue(); assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue();
@ -83,10 +79,8 @@ public class CasAuthenticationFilterTests {
@Test(expected = AuthenticationException.class) @Test(expected = AuthenticationException.class)
public void testNullServiceTicketHandledGracefully() throws Exception { public void testNullServiceTicketHandledGracefully() throws Exception {
CasAuthenticationFilter filter = new CasAuthenticationFilter(); CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager(new AuthenticationManager() { filter.setAuthenticationManager(a -> {
public Authentication authenticate(Authentication a) { throw new BadCredentialsException("Rejected");
throw new BadCredentialsException("Rejected");
}
}); });
filter.attemptAuthentication(new MockHttpServletRequest(), filter.attemptAuthentication(new MockHttpServletRequest(),

View File

@ -99,9 +99,7 @@ public final class WebSecurity extends
private SecurityExpressionHandler<FilterInvocation> expressionHandler = defaultWebSecurityExpressionHandler; private SecurityExpressionHandler<FilterInvocation> expressionHandler = defaultWebSecurityExpressionHandler;
private Runnable postBuildAction = new Runnable() { private Runnable postBuildAction = () -> {
public void run() {
}
}; };
/** /**

View File

@ -320,12 +320,10 @@ public abstract class WebSecurityConfigurerAdapter implements
public void init(final WebSecurity web) throws Exception { public void init(final WebSecurity web) throws Exception {
final HttpSecurity http = getHttp(); final HttpSecurity http = getHttp();
web.addSecurityFilterChainBuilder(http).postBuildAction(new Runnable() { web.addSecurityFilterChainBuilder(http).postBuildAction(() -> {
public void run() { FilterSecurityInterceptor securityInterceptor = http
FilterSecurityInterceptor securityInterceptor = http .getSharedObject(FilterSecurityInterceptor.class);
.getSharedObject(FilterSecurityInterceptor.class); web.securityInterceptor(securityInterceptor);
web.securityInterceptor(securityInterceptor);
}
}); });
} }

View File

@ -178,19 +178,9 @@ public class AnnotationParameterNameDiscoverer implements ParameterNameDiscovere
return null; return null;
} }
private static final ParameterNameFactory<Constructor<?>> CONSTRUCTOR_METHODPARAM_FACTORY = new ParameterNameFactory<Constructor<?>>() { private static final ParameterNameFactory<Constructor<?>> CONSTRUCTOR_METHODPARAM_FACTORY = constructor -> constructor.getParameterAnnotations();
public Annotation[][] findParameterAnnotations(Constructor<?> constructor) { private static final ParameterNameFactory<Method> METHOD_METHODPARAM_FACTORY = method -> method.getParameterAnnotations();
return constructor.getParameterAnnotations();
}
};
private static final ParameterNameFactory<Method> METHOD_METHODPARAM_FACTORY = new ParameterNameFactory<Method>() {
public Annotation[][] findParameterAnnotations(Method method) {
return method.getParameterAnnotations();
}
};
/** /**
* Strategy interface for looking up the parameter names. * Strategy interface for looking up the parameter names.

View File

@ -16,8 +16,6 @@
package org.springframework.security.core.userdetails.jdbc; package org.springframework.security.core.userdetails.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -27,7 +25,6 @@ import org.springframework.context.ApplicationContextException;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware; import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor; import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.core.SpringSecurityMessageSource;
@ -225,17 +222,12 @@ public class JdbcDaoImpl extends JdbcDaoSupport
*/ */
protected List<UserDetails> loadUsersByUsername(String username) { protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(this.usersByUsernameQuery, return getJdbcTemplate().query(this.usersByUsernameQuery,
new String[] { username }, new RowMapper<UserDetails>() { new String[] { username }, (rs, rowNum) -> {
@Override String username1 = rs.getString(1);
public UserDetails mapRow(ResultSet rs, int rowNum) String password = rs.getString(2);
throws SQLException { boolean enabled = rs.getBoolean(3);
String username = rs.getString(1); return new User(username1, password, enabled, true, true, true,
String password = rs.getString(2); AuthorityUtils.NO_AUTHORITIES);
boolean enabled = rs.getBoolean(3);
return new User(username, password, enabled, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
}
}); });
} }
@ -246,14 +238,10 @@ public class JdbcDaoImpl extends JdbcDaoSupport
*/ */
protected List<GrantedAuthority> loadUserAuthorities(String username) { protected List<GrantedAuthority> loadUserAuthorities(String username) {
return getJdbcTemplate().query(this.authoritiesByUsernameQuery, return getJdbcTemplate().query(this.authoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() { new String[] { username }, (rs, rowNum) -> {
@Override String roleName = JdbcDaoImpl.this.rolePrefix + rs.getString(2);
public GrantedAuthority mapRow(ResultSet rs, int rowNum)
throws SQLException {
String roleName = JdbcDaoImpl.this.rolePrefix + rs.getString(2);
return new SimpleGrantedAuthority(roleName); return new SimpleGrantedAuthority(roleName);
}
}); });
} }
@ -265,14 +253,10 @@ public class JdbcDaoImpl extends JdbcDaoSupport
*/ */
protected List<GrantedAuthority> loadGroupAuthorities(String username) { protected List<GrantedAuthority> loadGroupAuthorities(String username) {
return getJdbcTemplate().query(this.groupAuthoritiesByUsernameQuery, return getJdbcTemplate().query(this.groupAuthoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() { new String[] { username }, (rs, rowNum) -> {
@Override String roleName = getRolePrefix() + rs.getString(3);
public GrantedAuthority mapRow(ResultSet rs, int rowNum)
throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
return new SimpleGrantedAuthority(roleName); return new SimpleGrantedAuthority(roleName);
}
}); });
} }

View File

@ -32,16 +32,12 @@ import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.context.ApplicationContextException; import org.springframework.context.ApplicationContextException;
import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -176,20 +172,17 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
public void createUser(final UserDetails user) { public void createUser(final UserDetails user) {
validateUserDetails(user); validateUserDetails(user);
getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { getJdbcTemplate().update(createUserSql, ps -> {
@Override ps.setString(1, user.getUsername());
public void setValues(PreparedStatement ps) throws SQLException { ps.setString(2, user.getPassword());
ps.setString(1, user.getUsername()); ps.setBoolean(3, user.isEnabled());
ps.setString(2, user.getPassword());
ps.setBoolean(3, user.isEnabled());
int paramCount = ps.getParameterMetaData().getParameterCount(); int paramCount = ps.getParameterMetaData().getParameterCount();
if (paramCount > 3) { if (paramCount > 3) {
//NOTE: acc_locked, acc_expired and creds_expired are also to be inserted //NOTE: acc_locked, acc_expired and creds_expired are also to be inserted
ps.setBoolean(4, !user.isAccountNonLocked()); ps.setBoolean(4, !user.isAccountNonLocked());
ps.setBoolean(5, !user.isAccountNonExpired()); ps.setBoolean(5, !user.isAccountNonExpired());
ps.setBoolean(6, !user.isCredentialsNonExpired()); ps.setBoolean(6, !user.isCredentialsNonExpired());
}
} }
}); });
@ -201,25 +194,22 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
public void updateUser(final UserDetails user) { public void updateUser(final UserDetails user) {
validateUserDetails(user); validateUserDetails(user);
getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() { getJdbcTemplate().update(updateUserSql, ps -> {
@Override ps.setString(1, user.getPassword());
public void setValues(PreparedStatement ps) throws SQLException { ps.setBoolean(2, user.isEnabled());
ps.setString(1, user.getPassword());
ps.setBoolean(2, user.isEnabled());
int paramCount = ps.getParameterMetaData().getParameterCount(); int paramCount = ps.getParameterMetaData().getParameterCount();
if (paramCount == 3) { if (paramCount == 3) {
ps.setString(3, user.getUsername()); ps.setString(3, user.getUsername());
} else { } else {
//NOTE: acc_locked, acc_expired and creds_expired are also updated //NOTE: acc_locked, acc_expired and creds_expired are also updated
ps.setBoolean(3, !user.isAccountNonLocked()); ps.setBoolean(3, !user.isAccountNonLocked());
ps.setBoolean(4, !user.isAccountNonExpired()); ps.setBoolean(4, !user.isAccountNonExpired());
ps.setBoolean(5, !user.isCredentialsNonExpired()); ps.setBoolean(5, !user.isCredentialsNonExpired());
ps.setString(6, user.getUsername());
}
ps.setString(6, user.getUsername());
} }
}); });
if (getEnableAuthorities()) { if (getEnableAuthorities()) {
@ -337,11 +327,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
for (GrantedAuthority a : authorities) { for (GrantedAuthority a : authorities) {
final String authority = a.getAuthority(); final String authority = a.getAuthority();
getJdbcTemplate().update(insertGroupAuthoritySql, getJdbcTemplate().update(insertGroupAuthoritySql,
new PreparedStatementSetter() { ps -> {
public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, groupId);
ps.setInt(1, groupId); ps.setString(2, authority);
ps.setString(2, authority);
}
}); });
} }
} }
@ -351,11 +339,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.hasText(groupName, "groupName should have text"); Assert.hasText(groupName, "groupName should have text");
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() { PreparedStatementSetter groupIdPSS = ps -> ps.setInt(1, id);
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, id);
}
};
getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS); getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS);
getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS); getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS);
getJdbcTemplate().update(deleteGroupSql, groupIdPSS); getJdbcTemplate().update(deleteGroupSql, groupIdPSS);
@ -375,11 +359,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.hasText(groupName, "groupName should have text"); Assert.hasText(groupName, "groupName should have text");
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() { getJdbcTemplate().update(insertGroupMemberSql, ps -> {
public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, id);
ps.setInt(1, id); ps.setString(2, username);
ps.setString(2, username);
}
}); });
userCache.removeUserFromCache(username); userCache.removeUserFromCache(username);
@ -392,11 +374,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() { getJdbcTemplate().update(deleteGroupMemberSql, ps -> {
public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, id);
ps.setInt(1, id); ps.setString(2, username);
ps.setString(2, username);
}
}); });
userCache.removeUserFromCache(username); userCache.removeUserFromCache(username);
@ -407,13 +387,10 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.hasText(groupName, "groupName should have text"); Assert.hasText(groupName, "groupName should have text");
return getJdbcTemplate().query(groupAuthoritiesSql, new String[] { groupName }, return getJdbcTemplate().query(groupAuthoritiesSql, new String[] { groupName },
new RowMapper<GrantedAuthority>() { (rs, rowNum) -> {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) String roleName = getRolePrefix() + rs.getString(3);
throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
return new SimpleGrantedAuthority(roleName); return new SimpleGrantedAuthority(roleName);
}
}); });
} }
@ -425,12 +402,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() { getJdbcTemplate().update(deleteGroupAuthoritySql, ps -> {
ps.setInt(1, id);
public void setValues(PreparedStatement ps) throws SQLException { ps.setString(2, authority.getAuthority());
ps.setInt(1, id);
ps.setString(2, authority.getAuthority());
}
}); });
} }
@ -440,11 +414,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
Assert.notNull(authority, "authority cannot be null"); Assert.notNull(authority, "authority cannot be null");
final int id = findGroupId(groupName); final int id = findGroupId(groupName);
getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() { getJdbcTemplate().update(insertGroupAuthoritySql, ps -> {
public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, id);
ps.setInt(1, id); ps.setString(2, authority.getAuthority());
ps.setString(2, authority.getAuthority());
}
}); });
} }

View File

@ -19,15 +19,12 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import java.util.Collection;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
/** /**
@ -66,12 +63,7 @@ public class SecurityExpressionRootTests {
@Test @Test
public void roleHierarchySupportIsCorrectlyUsedInEvaluatingRoles() throws Exception { public void roleHierarchySupportIsCorrectlyUsedInEvaluatingRoles() throws Exception {
root.setRoleHierarchy(new RoleHierarchy() { root.setRoleHierarchy(authorities -> AuthorityUtils.createAuthorityList("ROLE_C"));
public Collection<GrantedAuthority> getReachableGrantedAuthorities(
Collection<? extends GrantedAuthority> authorities) {
return AuthorityUtils.createAuthorityList("ROLE_C");
}
});
assertThat(root.hasRole("C")).isTrue(); assertThat(root.hasRole("C")).isTrue();
assertThat(root.hasAuthority("ROLE_C")).isTrue(); assertThat(root.hasAuthority("ROLE_C")).isTrue();

View File

@ -75,11 +75,7 @@ public abstract class HierarchicalRolesTestHelper {
for (final String role : roles) { for (final String role : roles) {
// Use non SimpleGrantedAuthority (SEC-863) // Use non SimpleGrantedAuthority (SEC-863)
authorities.add(new GrantedAuthority() { authorities.add((GrantedAuthority) () -> role);
public String getAuthority() {
return role;
}
});
} }
return authorities; return authorities;

View File

@ -234,11 +234,7 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testLoginExceptionResolver() { public void testLoginExceptionResolver() {
assertThat(jaasProvider.getLoginExceptionResolver()).isNotNull(); assertThat(jaasProvider.getLoginExceptionResolver()).isNotNull();
jaasProvider.setLoginExceptionResolver(new LoginExceptionResolver() { jaasProvider.setLoginExceptionResolver(e -> new LockedException("This is just a test!"));
public AuthenticationException resolveException(LoginException e) {
return new LockedException("This is just a test!");
}
});
try { try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user",

View File

@ -16,8 +16,6 @@
package org.springframework.security.authentication.jaas; package org.springframework.security.authentication.jaas;
import java.security.Principal;
import java.util.Map; import java.util.Map;
import javax.security.auth.Subject; import javax.security.auth.Subject;
@ -77,17 +75,9 @@ public class TestLoginModule implements LoginModule {
throw new LoginException("Bad Password"); throw new LoginException("Bad Password");
} }
subject.getPrincipals().add(new Principal() { subject.getPrincipals().add(() -> "TEST_PRINCIPAL");
public String getName() {
return "TEST_PRINCIPAL";
}
});
subject.getPrincipals().add(new Principal() { subject.getPrincipals().add(() -> "NULL_PRINCIPAL");
public String getName() {
return "NULL_PRINCIPAL";
}
});
return true; return true;
} }

View File

@ -28,7 +28,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.core.task.SyncTaskExecutor; import org.springframework.core.task.SyncTaskExecutor;
@ -59,11 +58,9 @@ public class DelegatingSecurityContextRunnableTests {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
originalSecurityContext = SecurityContextHolder.createEmptyContext(); originalSecurityContext = SecurityContextHolder.createEmptyContext();
doAnswer(new Answer<Object>() { doAnswer((Answer<Object>) invocation -> {
public Object answer(InvocationOnMock invocation) throws Throwable { assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext); return null;
return null;
}
}).when(delegate).run(); }).when(delegate).run();
executor = Executors.newFixedThreadPool(1); executor = Executors.newFixedThreadPool(1);

View File

@ -48,14 +48,12 @@ public class UserDetailsByNameServiceWrapperTests {
UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper();
final User user = new User("dummy", "dummy", true, true, true, true, final User user = new User("dummy", "dummy", true, true, true, true,
AuthorityUtils.NO_AUTHORITIES); AuthorityUtils.NO_AUTHORITIES);
svc.setUserDetailsService(new UserDetailsService() { svc.setUserDetailsService(name -> {
public UserDetails loadUserByUsername(String name) { if (user != null && user.getUsername().equals(name)) {
if (user != null && user.getUsername().equals(name)) { return user;
return user; }
} else {
else { return null;
return null;
}
} }
}); });
svc.afterPropertiesSet(); svc.afterPropertiesSet();

View File

@ -33,8 +33,6 @@ import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.session.SessionDestroyedEvent; import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
/** /**
@ -70,23 +68,17 @@ public class ConcurrentSessionManagementTests extends AbstractWebServerIntegrati
// Now logout to kill first session // Now logout to kill first session
mockMvc.perform(post("/logout").with(csrf())) mockMvc.perform(post("/logout").with(csrf()))
.andExpect(status().is3xxRedirection()) .andExpect(status().is3xxRedirection())
.andDo(new ResultHandler() { .andDo(result -> context.publishEvent(new SessionDestroyedEvent(session1) {
@SuppressWarnings("serial")
@Override @Override
public void handle(MvcResult result) throws Exception { public List<SecurityContext> getSecurityContexts() {
context.publishEvent(new SessionDestroyedEvent(session1) { return Collections.emptyList();
@Override
public List<SecurityContext> getSecurityContexts() {
return Collections.emptyList();
}
@Override
public String getId() {
return session1.getId();
}
});
} }
});
@Override
public String getId() {
return session1.getId();
}
}));
// Try second session again // Try second session again
login2 = login() login2 = login()

View File

@ -85,11 +85,8 @@ public class SpringSecurityLdapTemplateITests extends AbstractLdapIntegrationTes
@Test @Test
public void namingExceptionIsTranslatedCorrectly() { public void namingExceptionIsTranslatedCorrectly() {
try { try {
template.executeReadOnly(new ContextExecutor() { template.executeReadOnly((ContextExecutor) dirContext -> {
public Object executeWithContext(DirContext dirContext) throw new NamingException();
throws NamingException {
throw new NamingException();
}
}); });
fail("Expected UncategorizedLdapException on NamingException"); fail("Expected UncategorizedLdapException on NamingException");
} }

View File

@ -134,15 +134,13 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
public DirContextOperations retrieveEntry(final String dn, public DirContextOperations retrieveEntry(final String dn,
final String[] attributesToRetrieve) { final String[] attributesToRetrieve) {
return (DirContextOperations) executeReadOnly(new ContextExecutor() { return (DirContextOperations) executeReadOnly((ContextExecutor) ctx -> {
public Object executeWithContext(DirContext ctx) throws NamingException { Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);
Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);
// Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx));
return new DirContextAdapter(attrs, new DistinguishedName(dn), return new DirContextAdapter(attrs, new DistinguishedName(dn),
new DistinguishedName(ctx.getNameInNamespace())); new DistinguishedName(ctx.getNameInNamespace()));
}
}); });
} }
@ -205,32 +203,30 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
final HashSet<Map<String, List<String>>> set = new HashSet<>(); final HashSet<Map<String, List<String>>> set = new HashSet<>();
ContextMapper roleMapper = new ContextMapper() { ContextMapper roleMapper = ctx -> {
public Object mapFromContext(Object ctx) { DirContextAdapter adapter = (DirContextAdapter) ctx;
DirContextAdapter adapter = (DirContextAdapter) ctx; Map<String, List<String>> record = new HashMap<>();
Map<String, List<String>> record = new HashMap<>(); if (attributeNames == null || attributeNames.length == 0) {
if (attributeNames == null || attributeNames.length == 0) { try {
try { for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae
for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae .hasMore();) {
.hasMore();) { Attribute attr = (Attribute) ae.next();
Attribute attr = (Attribute) ae.next(); extractStringAttributeValues(adapter, record, attr.getID());
extractStringAttributeValues(adapter, record, attr.getID());
}
}
catch (NamingException x) {
org.springframework.ldap.support.LdapUtils
.convertLdapException(x);
} }
} }
else { catch (NamingException x) {
for (String attributeName : attributeNames) { org.springframework.ldap.support.LdapUtils
extractStringAttributeValues(adapter, record, attributeName); .convertLdapException(x);
}
} }
record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
set.add(record);
return null;
} }
else {
for (String attributeName : attributeNames) {
extractStringAttributeValues(adapter, record, attributeName);
}
}
record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
set.add(record);
return null;
}; };
SearchControls ctls = new SearchControls(); SearchControls ctls = new SearchControls();
@ -313,12 +309,8 @@ public class SpringSecurityLdapTemplate extends LdapTemplate {
public DirContextOperations searchForSingleEntry(final String base, public DirContextOperations searchForSingleEntry(final String base,
final String filter, final Object[] params) { final String filter, final Object[] params) {
return (DirContextOperations) executeReadOnly(new ContextExecutor() { return (DirContextOperations) executeReadOnly((ContextExecutor) ctx -> searchForSingleEntryInternal(ctx, searchControls, base, filter,
public Object executeWithContext(DirContext ctx) throws NamingException { params));
return searchForSingleEntryInternal(ctx, searchControls, base, filter,
params);
}
});
} }
/** /**

View File

@ -25,14 +25,12 @@ import java.util.ListIterator;
import javax.naming.Context; import javax.naming.Context;
import javax.naming.NameNotFoundException; import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration; import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute; import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes; import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext; import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem; import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.ExtendedRequest; import javax.naming.ldap.ExtendedRequest;
import javax.naming.ldap.ExtendedResponse; import javax.naming.ldap.ExtendedResponse;
import javax.naming.ldap.LdapContext; import javax.naming.ldap.LdapContext;
@ -112,18 +110,15 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private final LdapTemplate template; private final LdapTemplate template;
/** Default context mapper used to create a set of roles from a list of attributes */ /** Default context mapper used to create a set of roles from a list of attributes */
private AttributesMapper roleMapper = new AttributesMapper() { private AttributesMapper roleMapper = attributes -> {
Attribute roleAttr = attributes.get(groupRoleAttributeName);
public Object mapFromAttributes(Attributes attributes) throws NamingException { NamingEnumeration<?> ne = roleAttr.getAll();
Attribute roleAttr = attributes.get(groupRoleAttributeName); // assert ne.hasMore();
Object group = ne.next();
String role = group.toString();
NamingEnumeration<?> ne = roleAttr.getAll(); return new SimpleGrantedAuthority(rolePrefix + role.toUpperCase());
// assert ne.hasMore();
Object group = ne.next();
String role = group.toString();
return new SimpleGrantedAuthority(rolePrefix + role.toUpperCase());
}
}; };
private String[] attributesToRetrieve; private String[] attributesToRetrieve;
@ -147,16 +142,14 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private DirContextAdapter loadUserAsContext(final DistinguishedName dn, private DirContextAdapter loadUserAsContext(final DistinguishedName dn,
final String username) { final String username) {
return (DirContextAdapter) template.executeReadOnly(new ContextExecutor() { return (DirContextAdapter) template.executeReadOnly((ContextExecutor) ctx -> {
public Object executeWithContext(DirContext ctx) throws NamingException { try {
try { Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);
Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx));
return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx)); }
} catch (NameNotFoundException notFound) {
catch (NameNotFoundException notFound) { throw new UsernameNotFoundException(
throw new UsernameNotFoundException( "User " + username + " not found", notFound);
"User " + username + " not found", notFound);
}
} }
}); });
} }
@ -217,16 +210,13 @@ public class LdapUserDetailsManager implements UserDetailsManager {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn,
final String username) { final String username) {
SearchExecutor se = new SearchExecutor() { SearchExecutor se = ctx -> {
public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
throws NamingException { SearchControls ctrls = new SearchControls();
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx); ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });
return ctx.search(groupSearchBase, groupSearchFilter, new String[] { return ctx.search(groupSearchBase, groupSearchFilter, new String[] {
fullDn.toUrl(), username }, ctrls); fullDn.toUrl(), username }, ctrls);
}
}; };
AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler( AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(
@ -339,19 +329,17 @@ public class LdapUserDetailsManager implements UserDetailsManager {
private void modifyAuthorities(final DistinguishedName userDn, private void modifyAuthorities(final DistinguishedName userDn,
final Collection<? extends GrantedAuthority> authorities, final int modType) { final Collection<? extends GrantedAuthority> authorities, final int modType) {
template.executeReadWrite(new ContextExecutor() { template.executeReadWrite((ContextExecutor) ctx -> {
public Object executeWithContext(DirContext ctx) throws NamingException { for (GrantedAuthority authority : authorities) {
for (GrantedAuthority authority : authorities) { String group = convertAuthorityToGroup(authority);
String group = convertAuthorityToGroup(authority); DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx);
DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx); ModificationItem addGroup = new ModificationItem(modType,
ModificationItem addGroup = new ModificationItem(modType, new BasicAttribute(groupMemberAttributeName, fullDn.toUrl()));
new BasicAttribute(groupMemberAttributeName, fullDn.toUrl()));
ctx.modifyAttributes(buildGroupDn(group), ctx.modifyAttributes(buildGroupDn(group),
new ModificationItem[] { addGroup }); new ModificationItem[] { addGroup });
}
return null;
} }
return null;
}); });
} }

View File

@ -36,12 +36,10 @@ import java.util.Map;
* @author Rob Winch * @author Rob Winch
*/ */
public final class SimpDestinationMessageMatcher implements MessageMatcher<Object> { public final class SimpDestinationMessageMatcher implements MessageMatcher<Object> {
public static final MessageMatcher<Object> NULL_DESTINATION_MATCHER = new MessageMatcher<Object>() { public static final MessageMatcher<Object> NULL_DESTINATION_MATCHER = message -> {
public boolean matches(Message<? extends Object> message) { String destination = SimpMessageHeaderAccessor.getDestination(message
String destination = SimpMessageHeaderAccessor.getDestination(message .getHeaders());
.getHeaders()); return destination == null;
return destination == null;
}
}; };
private final PathMatcher matcher; private final PathMatcher matcher;

View File

@ -176,11 +176,7 @@ public class OpenID4JavaConsumerTests {
new NullAxFetchListFactory()); new NullAxFetchListFactory());
VerificationResult vr = mock(VerificationResult.class); VerificationResult vr = mock(VerificationResult.class);
DiscoveryInformation di = mock(DiscoveryInformation.class); DiscoveryInformation di = mock(DiscoveryInformation.class);
Identifier id = new Identifier() { Identifier id = (Identifier) () -> "id";
public String getIdentifier() {
return "id";
}
};
Message msg = mock(Message.class); Message msg = mock(Message.class);
when( when(

View File

@ -29,8 +29,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
public class OpenIDAuthenticationFilterTests { public class OpenIDAuthenticationFilterTests {
@ -50,11 +48,7 @@ public class OpenIDAuthenticationFilterTests {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler()); filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
successHandler.setDefaultTargetUrl(DEFAULT_TARGET_URL); successHandler.setDefaultTargetUrl(DEFAULT_TARGET_URL);
filter.setAuthenticationManager(new AuthenticationManager() { filter.setAuthenticationManager(a -> a);
public Authentication authenticate(Authentication a) {
return a;
}
});
filter.afterPropertiesSet(); filter.afterPropertiesSet();
} }

View File

@ -16,13 +16,10 @@
package sample.contact; package sample.contact;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.core.support.JdbcDaoSupport;
/** /**
@ -38,44 +35,32 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
public void create(final Contact contact) { public void create(final Contact contact) {
getJdbcTemplate().update("insert into contacts values (?, ?, ?)", getJdbcTemplate().update("insert into contacts values (?, ?, ?)",
new PreparedStatementSetter() { ps -> {
public void setValues(PreparedStatement ps) throws SQLException { ps.setLong(1, contact.getId());
ps.setLong(1, contact.getId()); ps.setString(2, contact.getName());
ps.setString(2, contact.getName()); ps.setString(3, contact.getEmail());
ps.setString(3, contact.getEmail());
}
}); });
} }
public void delete(final Long contactId) { public void delete(final Long contactId) {
getJdbcTemplate().update("delete from contacts where id = ?", getJdbcTemplate().update("delete from contacts where id = ?",
new PreparedStatementSetter() { ps -> ps.setLong(1, contactId));
public void setValues(PreparedStatement ps) throws SQLException {
ps.setLong(1, contactId);
}
});
} }
public void update(final Contact contact) { public void update(final Contact contact) {
getJdbcTemplate().update( getJdbcTemplate().update(
"update contacts set contact_name = ?, address = ? where id = ?", "update contacts set contact_name = ?, address = ? where id = ?",
new PreparedStatementSetter() { ps -> {
public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, contact.getName());
ps.setString(1, contact.getName()); ps.setString(2, contact.getEmail());
ps.setString(2, contact.getEmail()); ps.setLong(3, contact.getId());
ps.setLong(3, contact.getId());
}
}); });
} }
public List<Contact> findAll() { public List<Contact> findAll() {
return getJdbcTemplate().query( return getJdbcTemplate().query(
"select id, contact_name, email from contacts order by id", "select id, contact_name, email from contacts order by id",
new RowMapper<Contact>() { (rs, rowNum) -> mapContact(rs));
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
return mapContact(rs);
}
});
} }
public List<String> findAllPrincipals() { public List<String> findAllPrincipals() {
@ -92,11 +77,7 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
public Contact getById(Long id) { public Contact getById(Long id) {
List<Contact> list = getJdbcTemplate().query( List<Contact> list = getJdbcTemplate().query(
"select id, contact_name, email from contacts where id = ? order by id", "select id, contact_name, email from contacts where id = ? order by id",
new RowMapper<Contact>() { (rs, rowNum) -> mapContact(rs), id);
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
return mapContact(rs);
}
}, id);
if (list.size() == 0) { if (list.size() == 0) {
return null; return null;

View File

@ -34,8 +34,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -166,12 +164,10 @@ public class DataSourcePopulator implements InitializingBean {
for (int i = 1; i < createEntities; i++) { for (int i = 1; i < createEntities; i++) {
final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class,
(long) i); (long) i);
tt.execute(new TransactionCallback<Object>() { tt.execute(arg0 -> {
public Object doInTransaction(TransactionStatus arg0) { mutableAclService.createAcl(objectIdentity);
mutableAclService.createAcl(objectIdentity);
return null; return null;
}
}); });
} }
@ -273,12 +269,10 @@ public class DataSourcePopulator implements InitializingBean {
} }
private void updateAclInTransaction(final MutableAcl acl) { private void updateAclInTransaction(final MutableAcl acl) {
tt.execute(new TransactionCallback<Object>() { tt.execute(arg0 -> {
public Object doInTransaction(TransactionStatus arg0) { mutableAclService.updateAcl(acl);
mutableAclService.updateAcl(acl);
return null; return null;
}
}); });
} }
} }

View File

@ -15,11 +15,8 @@
*/ */
package sample.dms; package sample.dms;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.util.FieldUtils; import org.springframework.security.util.FieldUtils;
import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionSynchronizationManager;
@ -80,23 +77,20 @@ public class DocumentDaoImpl extends JdbcDaoSupport implements DocumentDao {
/** Executes recursive SQL as needed to build a full Directory hierarchy of objects */ /** Executes recursive SQL as needed to build a full Directory hierarchy of objects */
private Directory getDirectoryWithImmediateParentPopulated(final Long id) { private Directory getDirectoryWithImmediateParentPopulated(final Long id) {
return getJdbcTemplate().queryForObject(SELECT_FROM_DIRECTORY_SINGLE, return getJdbcTemplate().queryForObject(SELECT_FROM_DIRECTORY_SINGLE,
new Object[] { id }, new RowMapper<Directory>() { new Object[] { id }, (rs, rowNumber) -> {
public Directory mapRow(ResultSet rs, int rowNumber) Long parentDirectoryId = rs
throws SQLException { .getLong("parent_directory_id");
Long parentDirectoryId = rs Directory parentDirectory = Directory.ROOT_DIRECTORY;
.getLong("parent_directory_id"); if (parentDirectoryId != null
Directory parentDirectory = Directory.ROOT_DIRECTORY; && !parentDirectoryId.equals(-1L)) {
if (parentDirectoryId != null // Need to go and lookup the parent, so do that first
&& !parentDirectoryId.equals(-1L)) { parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId);
// Need to go and lookup the parent, so do that first
parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId);
}
Directory directory = new Directory(rs
.getString("directory_name"), parentDirectory);
FieldUtils.setProtectedFieldValue("id", directory,
rs.getLong("id"));
return directory;
} }
Directory directory = new Directory(rs
.getString("directory_name"), parentDirectory);
FieldUtils.setProtectedFieldValue("id", directory,
rs.getLong("id"));
return directory;
}); });
} }
@ -105,38 +99,26 @@ public class DocumentDaoImpl extends JdbcDaoSupport implements DocumentDao {
"Directory required (the ID can be null to refer to root)"); "Directory required (the ID can be null to refer to root)");
if (directory.getId() == null) { if (directory.getId() == null) {
List<Directory> directories = getJdbcTemplate().query( List<Directory> directories = getJdbcTemplate().query(
SELECT_FROM_DIRECTORY_NULL, new RowMapper<Directory>() { SELECT_FROM_DIRECTORY_NULL, (rs, rowNumber) -> getDirectoryWithImmediateParentPopulated(rs
public Directory mapRow(ResultSet rs, int rowNumber) .getLong("id")));
throws SQLException {
return getDirectoryWithImmediateParentPopulated(rs
.getLong("id"));
}
});
return directories.toArray(new AbstractElement[] {}); return directories.toArray(new AbstractElement[] {});
} }
List<AbstractElement> directories = getJdbcTemplate().query( List<AbstractElement> directories = getJdbcTemplate().query(
SELECT_FROM_DIRECTORY, new Object[] { directory.getId() }, SELECT_FROM_DIRECTORY, new Object[] { directory.getId() },
new RowMapper<AbstractElement>() { (rs, rowNumber) -> getDirectoryWithImmediateParentPopulated(rs
public Directory mapRow(ResultSet rs, int rowNumber) .getLong("id")));
throws SQLException {
return getDirectoryWithImmediateParentPopulated(rs
.getLong("id"));
}
});
List<File> files = getJdbcTemplate().query(SELECT_FROM_FILE, List<File> files = getJdbcTemplate().query(SELECT_FROM_FILE,
new Object[] { directory.getId() }, new RowMapper<File>() { new Object[] { directory.getId() }, (rs, rowNumber) -> {
public File mapRow(ResultSet rs, int rowNumber) throws SQLException { Long parentDirectoryId = rs
Long parentDirectoryId = rs .getLong("parent_directory_id");
.getLong("parent_directory_id"); Directory parentDirectory = null;
Directory parentDirectory = null; if (parentDirectoryId != null) {
if (parentDirectoryId != null) { parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId);
parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId);
}
File file = new File(rs.getString("file_name"), parentDirectory);
FieldUtils.setProtectedFieldValue("id", file,
rs.getLong("id"));
return file;
} }
File file = new File(rs.getString("file_name"), parentDirectory);
FieldUtils.setProtectedFieldValue("id", file,
rs.getLong("id"));
return file;
}); });
// Add the File elements after the Directory elements // Add the File elements after the Directory elements
directories.addAll(files); directories.addAll(files);

View File

@ -15,10 +15,6 @@
*/ */
package sample.dms.secured; package sample.dms.secured;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.domain.PrincipalSid;
@ -49,11 +45,7 @@ public class SecureDocumentDaoImpl extends DocumentDaoImpl implements SecureDocu
public String[] getUsers() { public String[] getUsers() {
return getJdbcTemplate().query(SELECT_FROM_USERS, return getJdbcTemplate().query(SELECT_FROM_USERS,
new RowMapper<String>() { (rs, rowNumber) -> rs.getString("USERNAME")).toArray(new String[] {});
public String mapRow(ResultSet rs, int rowNumber) throws SQLException {
return rs.getString("USERNAME");
}
}).toArray(new String[] {});
} }
public void create(AbstractElement element) { public void create(AbstractElement element) {

View File

@ -147,20 +147,18 @@ public class ServletApiController {
@RequestMapping("/async") @RequestMapping("/async")
public void asynch(HttpServletRequest request, HttpServletResponse response) { public void asynch(HttpServletRequest request, HttpServletResponse response) {
final AsyncContext async = request.startAsync(); final AsyncContext async = request.startAsync();
async.start(new Runnable() { async.start(() -> {
public void run() { Authentication authentication = SecurityContextHolder.getContext()
Authentication authentication = SecurityContextHolder.getContext() .getAuthentication();
.getAuthentication(); try {
try { final HttpServletResponse asyncResponse = (HttpServletResponse) async
final HttpServletResponse asyncResponse = (HttpServletResponse) async .getResponse();
.getResponse(); asyncResponse.setStatus(HttpServletResponse.SC_OK);
asyncResponse.setStatus(HttpServletResponse.SC_OK); asyncResponse.getWriter().write(String.valueOf(authentication));
asyncResponse.getWriter().write(String.valueOf(authentication)); async.complete();
async.complete(); }
} catch (Exception e) {
catch (Exception e) { throw new RuntimeException(e);
throw new RuntimeException(e);
}
} }
}); });
} }
@ -211,4 +209,4 @@ public class ServletApiController {
public String login(@ModelAttribute LoginForm loginForm) { public String login(@ModelAttribute LoginForm loginForm) {
return "login"; return "login";
} }
} }

View File

@ -18,9 +18,7 @@ package org.springframework.security.taglibs.authz;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -146,11 +144,8 @@ public abstract class AbstractAuthorizeTag {
protected EvaluationContext createExpressionEvaluationContext( protected EvaluationContext createExpressionEvaluationContext(
SecurityExpressionHandler<FilterInvocation> handler) { SecurityExpressionHandler<FilterInvocation> handler) {
FilterInvocation f = new FilterInvocation(getRequest(), getResponse(), FilterInvocation f = new FilterInvocation(getRequest(), getResponse(),
new FilterChain() { (request, response) -> {
public void doFilter(ServletRequest request, ServletResponse response) throw new UnsupportedOperationException();
throws IOException, ServletException {
throw new UnsupportedOperationException();
}
}); });
return handler.createEvaluationContext(SecurityContextHolder.getContext() return handler.createEvaluationContext(SecurityContextHolder.getContext()

View File

@ -25,9 +25,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint; import org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter; import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
@ -59,13 +56,8 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests {
entryPoint.setKey("key"); entryPoint.setKey("key");
entryPoint.setRealmName("Spring Security"); entryPoint.setRealmName("Spring Security");
filter = new DigestAuthenticationFilter(); filter = new DigestAuthenticationFilter();
filter.setUserDetailsService(new UserDetailsService() { filter.setUserDetailsService(username -> new User(username, password, AuthorityUtils
public UserDetails loadUserByUsername(String username) .createAuthorityList("ROLE_USER")));
throws UsernameNotFoundException {
return new User(username, password, AuthorityUtils
.createAuthorityList("ROLE_USER"));
}
});
filter.setAuthenticationEntryPoint(entryPoint); filter.setAuthenticationEntryPoint(entryPoint);
filter.afterPropertiesSet(); filter.afterPropertiesSet();
} }
@ -133,4 +125,4 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests {
}); });
return username; return username;
} }
} }

View File

@ -16,13 +16,11 @@
package org.springframework.security.web; package org.springframework.security.web;
import java.io.IOException;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -48,11 +46,8 @@ import org.springframework.security.web.util.UrlUtils;
public class FilterInvocation { public class FilterInvocation {
// ~ Static fields // ~ Static fields
// ================================================================================================== // ==================================================================================================
static final FilterChain DUMMY_CHAIN = new FilterChain() { static final FilterChain DUMMY_CHAIN = (req, res) -> {
public void doFilter(ServletRequest req, ServletResponse res) throw new UnsupportedOperationException("Dummy filter chain");
throws IOException, ServletException {
throw new UnsupportedOperationException("Dummy filter chain");
}
}; };
// ~ Instance fields // ~ Instance fields

View File

@ -27,7 +27,6 @@ import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.util.ThrowableAnalyzer; import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.security.web.util.ThrowableCauseExtractor;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean; import org.springframework.web.filter.GenericFilterBean;
@ -241,12 +240,10 @@ public class ExceptionTranslationFilter extends GenericFilterBean {
protected void initExtractorMap() { protected void initExtractorMap() {
super.initExtractorMap(); super.initExtractorMap();
registerExtractor(ServletException.class, new ThrowableCauseExtractor() { registerExtractor(ServletException.class, throwable -> {
public Throwable extractCause(Throwable throwable) { ThrowableAnalyzer.verifyThrowableHierarchy(throwable,
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
ServletException.class); return ((ServletException) throwable).getRootCause();
return ((ServletException) throwable).getRootCause();
}
}); });
} }

View File

@ -18,11 +18,8 @@ package org.springframework.security.web.authentication.rememberme;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*; import java.util.*;
/** /**
@ -85,13 +82,8 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements
public PersistentRememberMeToken getTokenForSeries(String seriesId) { public PersistentRememberMeToken getTokenForSeries(String seriesId) {
try { try {
return getJdbcTemplate().queryForObject(tokensBySeriesSql, return getJdbcTemplate().queryForObject(tokensBySeriesSql,
new RowMapper<PersistentRememberMeToken>() { (rs, rowNum) -> new PersistentRememberMeToken(rs.getString(1), rs
public PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) .getString(2), rs.getString(3), rs.getTimestamp(4)), seriesId);
throws SQLException {
return new PersistentRememberMeToken(rs.getString(1), rs
.getString(2), rs.getString(3), rs.getTimestamp(4));
}
}, seriesId);
} }
catch (EmptyResultDataAccessException zeroResults) { catch (EmptyResultDataAccessException zeroResults) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {

View File

@ -91,11 +91,9 @@ public class JaasApiIntegrationFilter extends GenericFilterBean {
chain.doFilter(request, response); chain.doFilter(request, response);
return; return;
} }
final PrivilegedExceptionAction<Object> continueChain = new PrivilegedExceptionAction<Object>() { final PrivilegedExceptionAction<Object> continueChain = () -> {
public Object run() throws IOException, ServletException { chain.doFilter(request, response);
chain.doFilter(request, response); return null;
return null;
}
}; };
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
@ -160,4 +158,4 @@ public class JaasApiIntegrationFilter extends GenericFilterBean {
public final void setCreateEmptySubject(boolean createEmptySubject) { public final void setCreateEmptySubject(boolean createEmptySubject) {
this.createEmptySubject = createEmptySubject; this.createEmptySubject = createEmptySubject;
} }
} }

View File

@ -65,6 +65,7 @@ public abstract class ServerWebExchangeMatchers {
* Matches any exchange * Matches any exchange
* @return the matcher to use * @return the matcher to use
*/ */
@SuppressWarnings("Convert2Lambda")
public static ServerWebExchangeMatcher anyExchange() { public static ServerWebExchangeMatcher anyExchange() {
// we don't use a lambda to ensure a unique equals and hashcode // we don't use a lambda to ensure a unique equals and hashcode
// which otherwise can cause problems with adding multiple entries to an ordered LinkedHashMap // which otherwise can cause problems with adding multiple entries to an ordered LinkedHashMap

View File

@ -96,17 +96,12 @@ public class ConcurrentSessionFilter extends GenericFilterBean {
() -> expiredUrl + " isn't a valid redirect URL"); () -> expiredUrl + " isn't a valid redirect URL");
this.expiredUrl = expiredUrl; this.expiredUrl = expiredUrl;
this.sessionRegistry = sessionRegistry; this.sessionRegistry = sessionRegistry;
this.sessionInformationExpiredStrategy = new SessionInformationExpiredStrategy() { this.sessionInformationExpiredStrategy = event -> {
HttpServletRequest request = event.getRequest();
@Override HttpServletResponse response = event.getResponse();
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException { SessionInformation info = event.getSessionInformation();
HttpServletRequest request = event.getRequest();
HttpServletResponse response = event.getResponse();
SessionInformation info = event.getSessionInformation();
redirectStrategy.sendRedirect(request, response, determineExpiredUrl(request, info));
}
redirectStrategy.sendRedirect(request, response, determineExpiredUrl(request, info));
}; };
} }

View File

@ -40,22 +40,16 @@ public class ThrowableAnalyzer {
* *
* @see Throwable#getCause() * @see Throwable#getCause()
*/ */
public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = new ThrowableCauseExtractor() { public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = throwable -> throwable.getCause();
public Throwable extractCause(Throwable throwable) {
return throwable.getCause();
}
};
/** /**
* Default extractor for {@link InvocationTargetException} instances. * Default extractor for {@link InvocationTargetException} instances.
* *
* @see InvocationTargetException#getTargetException() * @see InvocationTargetException#getTargetException()
*/ */
public static final ThrowableCauseExtractor INVOCATIONTARGET_EXTRACTOR = new ThrowableCauseExtractor() { public static final ThrowableCauseExtractor INVOCATIONTARGET_EXTRACTOR = throwable -> {
public Throwable extractCause(Throwable throwable) { verifyThrowableHierarchy(throwable, InvocationTargetException.class);
verifyThrowableHierarchy(throwable, InvocationTargetException.class); return ((InvocationTargetException) throwable).getTargetException();
return ((InvocationTargetException) throwable).getTargetException();
}
}; };
/** /**
@ -64,21 +58,16 @@ public class ThrowableAnalyzer {
* greater by this comparator.<br> * greater by this comparator.<br>
* For hierarchically unrelated classes their fully qualified name will be compared. * For hierarchically unrelated classes their fully qualified name will be compared.
*/ */
private static final Comparator<Class<? extends Throwable>> CLASS_HIERARCHY_COMPARATOR = new Comparator<Class<? extends Throwable>>() { private static final Comparator<Class<? extends Throwable>> CLASS_HIERARCHY_COMPARATOR = (class1, class2) -> {
if (class1.isAssignableFrom(class2)) {
public int compare(Class<? extends Throwable> class1, return 1;
Class<? extends Throwable> class2) { }
if (class1.isAssignableFrom(class2)) { else if (class2.isAssignableFrom(class1)) {
return 1; return -1;
} }
else if (class2.isAssignableFrom(class1)) { else {
return -1; return class1.getName().compareTo(class2.getName());
}
else {
return class1.getName().compareTo(class2.getName());
}
} }
}; };
/** /**

View File

@ -21,7 +21,6 @@ import static org.mockito.Mockito.*;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
@ -55,15 +54,13 @@ public class FilterChainProxyTests {
public void setup() throws Exception { public void setup() throws Exception {
matcher = mock(RequestMatcher.class); matcher = mock(RequestMatcher.class);
filter = mock(Filter.class); filter = mock(Filter.class);
doAnswer(new Answer<Object>() { doAnswer((Answer<Object>) inv -> {
public Object answer(InvocationOnMock inv) throws Throwable { Object[] args = inv.getArguments();
Object[] args = inv.getArguments(); FilterChain fc = (FilterChain) args[2];
FilterChain fc = (FilterChain) args[2]; HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper(
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper( (HttpServletRequest) args[0]);
(HttpServletRequest) args[0]); fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]); return null;
return null;
}
}).when(filter).doFilter(any(), }).when(filter).doFilter(any(),
any(), any()); any(), any());
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher,
@ -187,12 +184,10 @@ public class FilterChainProxyTests {
@Test @Test
public void doFilterClearsSecurityContextHolder() throws Exception { public void doFilterClearsSecurityContextHolder() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true); when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer(new Answer<Object>() { doAnswer((Answer<Object>) inv -> {
public Object answer(InvocationOnMock inv) throws Throwable { SecurityContextHolder.getContext().setAuthentication(
SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken("username", "password"));
new TestingAuthenticationToken("username", "password")); return null;
return null;
}
}).when(filter).doFilter(any(HttpServletRequest.class), }).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class)); any(HttpServletResponse.class), any(FilterChain.class));
@ -204,12 +199,10 @@ public class FilterChainProxyTests {
@Test @Test
public void doFilterClearsSecurityContextHolderWithException() throws Exception { public void doFilterClearsSecurityContextHolderWithException() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true); when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer(new Answer<Object>() { doAnswer((Answer<Object>) inv -> {
public Object answer(InvocationOnMock inv) throws Throwable { SecurityContextHolder.getContext().setAuthentication(
SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken("username", "password"));
new TestingAuthenticationToken("username", "password")); throw new ServletException("oops");
throw new ServletException("oops");
}
}).when(filter).doFilter(any(HttpServletRequest.class), }).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class)); any(HttpServletResponse.class), any(FilterChain.class));
@ -228,23 +221,19 @@ public class FilterChainProxyTests {
public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception { public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception {
final FilterChain innerChain = mock(FilterChain.class); final FilterChain innerChain = mock(FilterChain.class);
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true); when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer(new Answer<Object>() { doAnswer((Answer<Object>) inv -> {
public Object answer(InvocationOnMock inv) throws Throwable { TestingAuthenticationToken expected = new TestingAuthenticationToken(
TestingAuthenticationToken expected = new TestingAuthenticationToken( "username", "password");
"username", "password"); SecurityContextHolder.getContext().setAuthentication(expected);
SecurityContextHolder.getContext().setAuthentication(expected); doAnswer((Answer<Object>) inv1 -> {
doAnswer(new Answer<Object>() { innerChain.doFilter(request, response);
public Object answer(InvocationOnMock inv) throws Throwable {
innerChain.doFilter(request, response);
return null;
}
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
fcp.doFilter(request, response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null; return null;
} }).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
fcp.doFilter(request, response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).when(filter).doFilter(any(HttpServletRequest.class), }).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class)); any(HttpServletResponse.class), any(FilterChain.class));

View File

@ -44,7 +44,6 @@ import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
@ -324,11 +323,5 @@ public class ExceptionTranslationFilterTests {
verifyZeroInteractions(mockEntryPoint); verifyZeroInteractions(mockEntryPoint);
} }
private AuthenticationEntryPoint mockEntryPoint = new AuthenticationEntryPoint() { private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response.sendRedirect(request.getContextPath() + "/login.jsp");
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException,
ServletException {
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
};
} }

View File

@ -22,7 +22,6 @@ import static org.assertj.core.api.Assertions.*;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import org.junit.Test; import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
@ -161,12 +160,7 @@ public class UsernamePasswordAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() { private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer( when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() { (Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
return am; return am;
} }

View File

@ -30,7 +30,6 @@ import javax.servlet.http.HttpServletRequest;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
@ -396,12 +395,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
} }
else { else {
when(am.authenticate(any(Authentication.class))).thenAnswer( when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() { (Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
} }
filter.setAuthenticationManager(am); filter.setAuthenticationManager(am);

View File

@ -126,17 +126,13 @@ public class PreAuthenticatedAuthenticationProviderTests {
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService( private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService(
final UserDetails aUserDetails) { final UserDetails aUserDetails) {
return new AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>() { return token -> {
if (aUserDetails != null
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) && aUserDetails.getUsername().equals(token.getName())) {
throws UsernameNotFoundException { return aUserDetails;
if (aUserDetails != null
&& aUserDetails.getUsername().equals(token.getName())) {
return aUserDetails;
}
throw new UsernameNotFoundException("notfound");
} }
throw new UsernameNotFoundException("notfound");
}; };
} }

View File

@ -67,11 +67,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
userName, "dummy"); userName, "dummy");
token.setDetails(new GrantedAuthoritiesContainer() { token.setDetails((GrantedAuthoritiesContainer) () -> gas);
public Collection<? extends GrantedAuthority> getGrantedAuthorities() {
return gas;
}
});
UserDetails ud = svc.loadUserDetails(token); UserDetails ud = svc.loadUserDetails(token);
assertThat(ud.isAccountNonExpired()).isTrue(); assertThat(ud.isAccountNonExpired()).isTrue();
assertThat(ud.isAccountNonLocked()).isTrue(); assertThat(ud.isAccountNonLocked()).isTrue();

View File

@ -21,7 +21,6 @@ import static org.mockito.Mockito.*;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
@ -29,8 +28,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
import org.springframework.security.web.authentication.preauth.RequestAttributeAuthenticationFilter;
/** /**
* *
@ -159,12 +156,7 @@ public class RequestAttributeAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() { private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))) when(am.authenticate(any(Authentication.class)))
.thenAnswer(new Answer<Authentication>() { .thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
return am; return am;
} }

View File

@ -21,7 +21,6 @@ import static org.mockito.Mockito.*;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
@ -152,12 +151,7 @@ public class RequestHeaderAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() { private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer( when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() { (Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
return am; return am;
} }

View File

@ -17,7 +17,6 @@ package org.springframework.security.web.authentication.preauth.j2ee;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.security.Principal;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@ -60,12 +59,7 @@ public class J2eePreAuthenticatedProcessingFilterTests {
} }
}; };
req.setRemoteUser(aUserName); req.setRemoteUser(aUserName);
req.setUserPrincipal(new Principal() { req.setUserPrincipal(() -> aUserName);
public String getName() {
return aUserName;
}
});
return req; return req;
} }

View File

@ -21,7 +21,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.junit.*; import org.junit.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
@ -56,12 +55,7 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer( when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() { (Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
filter.setAuthenticationManager(am); filter.setAuthenticationManager(am);
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource( WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(

View File

@ -439,14 +439,10 @@ public class SwitchUserFilterTests {
SwitchUserFilter filter = new SwitchUserFilter(); SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService()); filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchUserAuthorityChanger(new SwitchUserAuthorityChanger() { filter.setSwitchUserAuthorityChanger((targetUser, currentAuthentication, authoritiesToBeGranted) -> {
public Collection<GrantedAuthority> modifyGrantedAuthorities( List<GrantedAuthority> auths = new ArrayList<>();
UserDetails targetUser, Authentication currentAuthentication, auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
Collection<? extends GrantedAuthority> authoritiesToBeGranted) { return auths;
List<GrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
return auths;
}
}); });
Authentication result = filter.attemptSwitchUser(request); Authentication result = filter.attemptSwitchUser(request);

View File

@ -38,7 +38,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache; import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -131,14 +130,8 @@ public class DigestAuthenticationFilterTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
// Create User Details Service // Create User Details Service
UserDetailsService uds = new UserDetailsService() { UserDetailsService uds = username -> new User("rod,ok", "koala",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
return new User("rod,ok", "koala",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
}
};
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName(REALM); ep.setRealmName(REALM);

View File

@ -20,7 +20,6 @@ import static org.mockito.Mockito.*;
import java.io.IOException; import java.io.IOException;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
@ -91,13 +90,10 @@ public class SecurityContextPersistenceFilterTests {
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore); when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
final FilterChain chain = new FilterChain() { final FilterChain chain = (request1, response1) -> {
public void doFilter(ServletRequest request, ServletResponse response) assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth);
throws IOException, ServletException { // Change the context here
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth); SecurityContextHolder.setContext(scExpectedAfter);
// Change the context here
SecurityContextHolder.setContext(scExpectedAfter);
}
}; };
filter.doFilter(request, response, chain); filter.doFilter(request, response, chain);

View File

@ -15,16 +15,11 @@
*/ */
package org.springframework.security.web.header; package org.springframework.security.web.header;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -100,17 +95,13 @@ public class HeaderWriterFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new FilterChain() { filter.doFilter(request, response, (request1, response1) -> {
@Override verifyZeroInteractions(HeaderWriterFilterTests.this.writer1);
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
verifyZeroInteractions(HeaderWriterFilterTests.this.writer1);
response.flushBuffer(); response1.flushBuffer();
verify(HeaderWriterFilterTests.this.writer1).writeHeaders( verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class)); any(HttpServletRequest.class), any(HttpServletResponse.class));
}
}); });
verifyNoMoreInteractions(this.writer1); verifyNoMoreInteractions(this.writer1);
@ -146,14 +137,8 @@ public class HeaderWriterFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new FilterChain() { filter.doFilter(request, response, (request1, response1) -> verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
@Override any(HttpServletRequest.class), any(HttpServletResponse.class)));
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
});
verifyNoMoreInteractions(this.writer1); verifyNoMoreInteractions(this.writer1);
} }

View File

@ -20,7 +20,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException; import java.io.IOException;
import java.security.AccessController; import java.security.AccessController;
import java.security.Principal;
import java.util.HashMap; import java.util.HashMap;
import javax.security.auth.Subject; import javax.security.auth.Subject;
@ -84,33 +83,24 @@ public class JaasApiIntegrationFilterTests {
this.response = new MockHttpServletResponse(); this.response = new MockHttpServletResponse();
authenticatedSubject = new Subject(); authenticatedSubject = new Subject();
authenticatedSubject.getPrincipals().add(new Principal() { authenticatedSubject.getPrincipals().add(() -> "principal");
public String getName() {
return "principal";
}
});
authenticatedSubject.getPrivateCredentials().add("password"); authenticatedSubject.getPrivateCredentials().add("password");
authenticatedSubject.getPublicCredentials().add("username"); authenticatedSubject.getPublicCredentials().add("username");
callbackHandler = new CallbackHandler() { callbackHandler = callbacks -> {
for (Callback callback : callbacks) {
public void handle(Callback[] callbacks) if (callback instanceof NameCallback) {
throws IOException, UnsupportedCallbackException { ((NameCallback) callback).setName("user");
for (Callback callback : callbacks) { }
if (callback instanceof NameCallback) { else if (callback instanceof PasswordCallback) {
((NameCallback) callback).setName("user"); ((PasswordCallback) callback).setPassword(
} "password".toCharArray());
else if (callback instanceof PasswordCallback) { }
((PasswordCallback) callback).setPassword( else if (callback instanceof TextInputCallback) {
"password".toCharArray()); // ignore
} }
else if (callback instanceof TextInputCallback) { else {
// ignore throw new UnsupportedCallbackException(callback,
} "Unrecognized Callback " + callback);
else {
throw new UnsupportedCallbackException(callback,
"Unrecognized Callback " + callback);
}
} }
} }
}; };

View File

@ -30,7 +30,6 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.PortResolverImpl; import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.util.matcher.RequestMatcher;
/** /**
* *
@ -62,12 +61,7 @@ public class HttpSessionRequestCacheTests {
@Test @Test
public void requestMatcherDefinesCorrectSubsetOfCachedRequests() throws Exception { public void requestMatcherDefinesCorrectSubsetOfCachedRequests() throws Exception {
HttpSessionRequestCache cache = new HttpSessionRequestCache(); HttpSessionRequestCache cache = new HttpSessionRequestCache();
cache.setRequestMatcher(new RequestMatcher() { cache.setRequestMatcher(request -> request.getMethod().equals("GET"));
public boolean matches(HttpServletRequest request) {
return request.getMethod().equals("GET");
}
});
MockHttpServletRequest request = new MockHttpServletRequest("POST", MockHttpServletRequest request = new MockHttpServletRequest("POST",
"/destination"); "/destination");

View File

@ -317,11 +317,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
SecurityContextHolder.setContext(context); SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class); AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.getAsyncContext()).thenReturn(asyncContext); when(this.request.getAsyncContext()).thenReturn(asyncContext);
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override
public void run() {
}
}; };
wrappedRequest().getAsyncContext().start(runnable); wrappedRequest().getAsyncContext().start(runnable);
@ -346,11 +342,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
SecurityContextHolder.setContext(context); SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class); AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.startAsync()).thenReturn(asyncContext); when(this.request.startAsync()).thenReturn(asyncContext);
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override
public void run() {
}
}; };
wrappedRequest().startAsync().start(runnable); wrappedRequest().startAsync().start(runnable);
@ -376,11 +368,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
AsyncContext asyncContext = mock(AsyncContext.class); AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.startAsync(this.request, this.response)) when(this.request.startAsync(this.request, this.response))
.thenReturn(asyncContext); .thenReturn(asyncContext);
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override
public void run() {
}
}; };
wrappedRequest().startAsync(this.request, this.response).start(runnable); wrappedRequest().startAsync(this.request, this.response).start(runnable);