Tidying up to remove warnings (generics, use of deprecated test classes etc).

This commit is contained in:
Luke Taylor 2009-04-28 06:49:43 +00:00
parent f38c0eb675
commit e94baf38b3
27 changed files with 150 additions and 177 deletions

View File

@ -49,7 +49,7 @@ public class AuthorityUtilsTests {
@Test
public void commaSeparatedStringIsParsedCorrectly() {
List<GrantedAuthority> authorityArray =
AuthorityUtils.commaSeparatedStringToAuthorityList(" ROLE_A, B, C, ROLE_D, E ");
AuthorityUtils.commaSeparatedStringToAuthorityList(" ROLE_A, B, C, ROLE_D\n,\n E ");
Set<String> authorities = AuthorityUtils.authorityListToSet(authorityArray);

View File

@ -7,6 +7,7 @@ import org.springframework.transaction.annotation.Transactional;
public class UserDetailsServiceImpl implements UserDetailsService {
@SuppressWarnings("unused")
private UserRepository userRepository;
@Transactional(readOnly=true)

View File

@ -25,7 +25,7 @@ public abstract class AbstractWebServerIntegrationTests {
private final Object SERVER_LOCK = new Object();
protected final WebTester tester = new WebTester();
/**
/**
* Override to set the application context files that should be loaded or return null
* to use web.xml.
*/
@ -49,15 +49,16 @@ public abstract class AbstractWebServerIntegrationTests {
}
}
}
@SuppressWarnings("unchecked")
protected WebAppContext createWebContext() {
WebAppContext webCtx = new WebAppContext("src/main/webapp", getContextPath());
if (StringUtils.hasText(getContextConfigLocations())) {
webCtx.addEventListener(new ContextLoaderListener());
webCtx.getInitParams().put("contextConfigLocation", getContextConfigLocations());
}
return webCtx;
}
@ -70,12 +71,12 @@ public abstract class AbstractWebServerIntegrationTests {
server = null;
}
}
@AfterMethod
public void resetWebConversation() {
tester.getTestContext().setWebClient(new WebConversation());
}
private final String getBaseUrl() {
int port = server.getConnectors()[0].getLocalPort();
return "http://localhost:" + port + getContextPath() + "/";
@ -84,7 +85,7 @@ public abstract class AbstractWebServerIntegrationTests {
protected final Object getBean(String beanName) {
return getAppContext().getBean(beanName);
}
private WebApplicationContext getAppContext() {
ServletContext servletCtx = ((WebAppContext)server.getHandler()).getServletContext();
WebApplicationContext appCtx =
@ -116,14 +117,14 @@ public abstract class AbstractWebServerIntegrationTests {
tester.assertTextPresent(text);
}
// Security-specific utility methods
// Security-specific utility methods
protected void login(String username, String password) {
assertFormPresent();
setFormElement("j_username", username);
setFormElement("j_password", password);
submit();
submit();
}
}

View File

@ -59,9 +59,10 @@ public class OpenID4JavaConsumer implements OpenIDConsumer {
return beginConsumption(req, identityUrl, returnToUrl, returnToUrl);
}
@SuppressWarnings("unchecked")
public String beginConsumption(HttpServletRequest req, String identityUrl, String returnToUrl, String realm)
throws OpenIDConsumerException {
List discoveries;
List<DiscoveryInformation> discoveries;
try {
discoveries = consumerManager.discover(identityUrl);

View File

@ -15,20 +15,16 @@
package org.springframework.security.openid;
import junit.framework.TestCase;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.AuthorityUtils;
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.openid.AuthenticationCancelledException;
import org.springframework.security.openid.OpenIDAuthenticationProvider;
import org.springframework.security.openid.OpenIDAuthenticationStatus;
import org.springframework.security.openid.OpenIDAuthenticationToken;
/**
@ -201,10 +197,9 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
}
static class MockUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(String ssoUserId)
throws AuthenticationException {
public UserDetails loadUserByUsername(String ssoUserId) throws AuthenticationException {
return new User(ssoUserId, "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"));
}
}
}

View File

@ -16,24 +16,18 @@
package sample.contact;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.util.StopWatch;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Demonstrates accessing the {@link ContactManager} via remoting protocols.
@ -57,13 +51,11 @@ public class ClientApplication {
public void invokeContactManager(Authentication authentication, int nrOfCalls) {
StopWatch stopWatch = new StopWatch(nrOfCalls + " ContactManager call(s)");
Map contactServices = this.beanFactory.getBeansOfType(ContactManager.class, true, true);
Map<String, ContactManager> contactServices = this.beanFactory.getBeansOfType(ContactManager.class, true, true);
SecurityContextHolder.getContext().setAuthentication(authentication);
for (Iterator it = contactServices.keySet().iterator(); it.hasNext();) {
String beanName = (String) it.next();
for (String beanName : contactServices.keySet()) {
Object object = this.beanFactory.getBean("&" + beanName);
try {
@ -91,12 +83,12 @@ public class ClientApplication {
} catch (IllegalAccessException ignored) {}
catch (InvocationTargetException ignored) {}
ContactManager remoteContactManager = (ContactManager) contactServices.get(beanName);
ContactManager remoteContactManager = contactServices.get(beanName);
System.out.println("Calling ContactManager '" + beanName + "'");
stopWatch.start(beanName);
List contacts = null;
List<Contact> contacts = null;
for (int i = 0; i < nrOfCalls; i++) {
contacts = remoteContactManager.getAll();
@ -105,11 +97,8 @@ public class ClientApplication {
stopWatch.stop();
if (contacts.size() != 0) {
Iterator listIterator = contacts.iterator();
while (listIterator.hasNext()) {
Contact contact = (Contact) listIterator.next();
System.out.println("Contact: " + contact.toString());
for(Contact contact : contacts) {
System.out.println("Contact: " + contact);
}
} else {
System.out.println("No contacts found which this user has permission to");

View File

@ -70,7 +70,7 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
}
public Contact getById(Long id) {
List list = contactsByIdQuery.execute(id.longValue());
List<Contact> list = contactsByIdQuery.execute(id.longValue());
if (list.size() == 0) {
return null;
@ -89,24 +89,20 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
contactsByIdQuery = new ContactsByIdQuery(getDataSource());
}
private String makeObjectIdentity(Contact contact) {
return contact.getClass().getName() + ":" + contact.getId();
}
public void update(Contact contact) {
contactUpdate.update(contact);
}
//~ Inner Classes ==================================================================================================
protected class AclObjectIdentityByObjectIdentityQuery extends MappingSqlQuery {
protected class AclObjectIdentityByObjectIdentityQuery extends MappingSqlQuery<Long> {
protected AclObjectIdentityByObjectIdentityQuery(DataSource ds) {
super(ds, "SELECT id FROM acl_object_identity WHERE object_identity = ?");
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
protected Object mapRow(ResultSet rs, int rownum)
protected Long mapRow(ResultSet rs, int rownum)
throws SQLException {
return new Long(rs.getLong("id"));
}
@ -172,14 +168,13 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
}
}
protected class ContactsAllQuery extends MappingSqlQuery {
protected class ContactsAllQuery extends MappingSqlQuery<Contact> {
protected ContactsAllQuery(DataSource ds) {
super(ds, "SELECT id, contact_name, email FROM contacts ORDER BY id");
compile();
}
protected Object mapRow(ResultSet rs, int rownum)
throws SQLException {
protected Contact mapRow(ResultSet rs, int rownum) throws SQLException {
Contact contact = new Contact();
contact.setId(new Long(rs.getLong("id")));
contact.setName(rs.getString("contact_name"));
@ -189,15 +184,14 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
}
}
protected class ContactsByIdQuery extends MappingSqlQuery {
protected class ContactsByIdQuery extends MappingSqlQuery<Contact> {
protected ContactsByIdQuery(DataSource ds) {
super(ds, "SELECT id, contact_name, email FROM contacts WHERE id = ? ORDER BY id");
declareParameter(new SqlParameter(Types.BIGINT));
compile();
}
protected Object mapRow(ResultSet rs, int rownum)
throws SQLException {
protected Contact mapRow(ResultSet rs, int rownum) throws SQLException {
Contact contact = new Contact();
contact.setId(new Long(rs.getLong("id")));
contact.setName(rs.getString("contact_name"));
@ -238,26 +232,24 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
}
}
protected class PrincipalsAllQuery extends MappingSqlQuery {
protected class PrincipalsAllQuery extends MappingSqlQuery<String> {
protected PrincipalsAllQuery(DataSource ds) {
super(ds, "SELECT username FROM users ORDER BY username");
compile();
}
protected Object mapRow(ResultSet rs, int rownum)
throws SQLException {
protected String mapRow(ResultSet rs, int rownum) throws SQLException {
return rs.getString("username");
}
}
protected class RolesAllQuery extends MappingSqlQuery {
protected class RolesAllQuery extends MappingSqlQuery<String> {
protected RolesAllQuery(DataSource ds) {
super(ds, "SELECT DISTINCT authority FROM authorities ORDER BY authority");
compile();
}
protected Object mapRow(ResultSet rs, int rownum)
throws SQLException {
protected String mapRow(ResultSet rs, int rownum) throws SQLException {
return rs.getString("authority");
}
}

View File

@ -165,7 +165,7 @@ public class ContactManagerBackend extends ApplicationObjectSupport implements C
}
Random rnd = new Random();
List contacts = contactDao.findAll();
List<Contact> contacts = contactDao.findAll();
int getNumber = rnd.nextInt(contacts.size());
return (Contact) contacts.get(getNumber);

View File

@ -163,7 +163,7 @@ public class DataSourcePopulator implements InitializingBean {
// Create acl_object_identity rows (and also acl_class rows as needed
for (int i = 1; i < createEntities; i++) {
final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, new Long(i));
tt.execute(new TransactionCallback() {
tt.execute(new TransactionCallback<Object>() {
public Object doInTransaction(TransactionStatus arg0) {
mutableAclService.createAcl(objectIdentity);
@ -263,7 +263,7 @@ public class DataSourcePopulator implements InitializingBean {
}
private void updateAclInTransaction(final MutableAcl acl) {
tt.execute(new TransactionCallback() {
tt.execute(new TransactionCallback<Object>() {
public Object doInTransaction(TransactionStatus arg0) {
mutableAclService.updateAcl(acl);

View File

@ -14,22 +14,7 @@
*/
package sample.contact;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ -37,6 +22,17 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
* Controller for deleting an ACL permission.
@ -71,7 +67,7 @@ public class DeletePermissionController implements Controller, InitializingBean
contactManager.deletePermission(contact, sidObject, permission);
Map model = new HashMap();
Map<String, Object> model = new HashMap<String, Object>();
model.put("contact", contact);
model.put("sid", sidObject);
model.put("permission", permission);

View File

@ -85,7 +85,7 @@ public class SecureIndexController implements Controller, InitializingBean {
permissionEvaluator.hasPermission(user, contact, HAS_ADMIN) ? Boolean.TRUE : Boolean.FALSE);
}
Map model = new HashMap();
Map<String, Object> model = new HashMap<String, Object>();
model.put("contacts", myContactsList);
model.put("hasDeletePermission", hasDelete);
model.put("hasAdminPermission", hasAdmin);

View File

@ -6,8 +6,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
@ -74,8 +73,8 @@ public class DataSourcePopulator implements InitializingBean {
template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
// Now create an ACL entry for the root directory
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("rod", "ignored", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_IGNORED")}));
tt.execute(new TransactionCallback() {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("rod", "ignored", AuthorityUtils.createAuthorityList(("ROLE_IGNORED"))));
tt.execute(new TransactionCallback<Object>() {
public Object doInTransaction(TransactionStatus arg0) {
addPermission(documentDao, Directory.ROOT_DIRECTORY, "ROLE_USER", LEVEL_GRANT_WRITE);
return null;
@ -147,4 +146,4 @@ public class DataSourcePopulator implements InitializingBean {
* @param level based on the static final integer fields on this class
*/
protected void addPermission(DocumentDao documentDao, AbstractElement element, String recipient, int level) {}
}
}

View File

@ -38,7 +38,7 @@ public class SecureDataSourcePopulator extends DataSourcePopulator {
Assert.notNull(SecurityContextHolder.getContext().getAuthentication(), "SecurityContextHolder must contain an Authentication");
// We need SecureDocumentDao to assign different permissions
SecureDocumentDao dao = (SecureDocumentDao) documentDao;
//SecureDocumentDao dao = (SecureDocumentDao) documentDao;
// We need to construct an ACL-specific Sid. Note the prefix contract is defined on the superclass method's JavaDocs
Sid sid = null;

View File

@ -34,8 +34,8 @@ public class SecureDocumentDaoImpl extends DocumentDaoImpl implements SecureDocu
}
public String[] getUsers() {
return (String[]) getJdbcTemplate().query(SELECT_FROM_USERS, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
return (String[]) getJdbcTemplate().query(SELECT_FROM_USERS, new RowMapper<String>() {
public String mapRow(ResultSet rs, int rowNumber) throws SQLException {
return rs.getString("USERNAME");
}
}).toArray(new String[] {});

View File

@ -9,6 +9,10 @@
<beans>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:insecuredms"/>
@ -16,23 +20,23 @@
<property name="password" value=""/>
</bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionAttributeSource">
<value>
sample.dms.DocumentDao.*=PROPAGATION_REQUIRED
</value>
</property>
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionAttributeSource">
<value>
sample.dms.DocumentDao.*=PROPAGATION_REQUIRED
</value>
</property>
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="documentDao" class="sample.dms.DocumentDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSourcePopulator" class="sample.dms.DataSourcePopulator">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="documentDao"/>
<constructor-arg ref="transactionManager"/>
</bean>
<bean id="documentDao" class="sample.dms.DocumentDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSourcePopulator" class="sample.dms.DataSourcePopulator">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="documentDao"/>
<constructor-arg ref="transactionManager"/>
</bean>
</beans>

View File

@ -8,6 +8,9 @@
-->
<beans>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>

View File

@ -1,6 +1,13 @@
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import sample.dms.AbstractElement;
import sample.dms.Directory;
@ -13,14 +20,21 @@ import sample.dms.DocumentDao;
* @version $Id$
*
*/
public class DmsIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests {
@ContextConfiguration(locations={"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-insecure.xml"})
public class DmsIntegrationTests extends AbstractTransactionalJUnit4SpringContextTests{
@Autowired
protected JdbcTemplate jdbcTemplate;
@Autowired
protected DocumentDao documentDao;
protected String[] getConfigLocations() {
return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-insecure.xml"};
}
protected void onTearDown() throws Exception {
@After
public void clearContext() {
SecurityContextHolder.clearContext();
}
@ -28,20 +42,24 @@ public class DmsIntegrationTests extends AbstractTransactionalDataSourceSpringCo
this.documentDao = documentDao;
}
@Test
public void testBasePopulation() {
assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY"));
assertEquals(90, jdbcTemplate.queryForInt("select count(id) from FILE"));
assertEquals(3, documentDao.findElements(Directory.ROOT_DIRECTORY).length);
}
@Test
public void testMarissaRetrieval() {
process("rod", "koala", false);
}
@Test
public void testScottRetrieval() {
process("scott", "wombat", false);
}
@Test
public void testDianneRetrieval() {
process("dianne", "emu", false);
}

View File

@ -1,4 +1,7 @@
import org.springframework.security.acls.AclService;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
@ -9,18 +12,17 @@ import org.springframework.security.acls.AclService;
* @version $Id$
*
*/
@ContextConfiguration(locations={"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-secure.xml"})
public class SecureDmsIntegrationTests extends DmsIntegrationTests {
private AclService aclService;
public void setAclService(AclService aclService) {
this.aclService = aclService;
}
// @Autowired
// private AclService aclService;
protected String[] getConfigLocations() {
return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-secure.xml"};
}
@Test
public void testBasePopulation() {
assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY"));
assertEquals(90, jdbcTemplate.queryForInt("select count(id) from FILE"));

View File

@ -3,7 +3,6 @@ package bigbank.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
@ -13,7 +12,7 @@ import bigbank.BankService;
public class ListAccounts implements Controller {
private BankService bankService;
public ListAccounts(BankService bankService) {
Assert.notNull(bankService);
this.bankService = bankService;
@ -24,7 +23,7 @@ public class ListAccounts implements Controller {
// if (request.getUserPrincipal() == null) {
// throw new AuthenticationCredentialsNotFoundException("You must login to view the account list (Spring Security message)"); // only for Spring Security managed authentication
// }
// Actual business logic
ModelAndView mav = new ModelAndView("listAccounts");
mav.addObject("accounts", bankService.findAccounts());

View File

@ -169,6 +169,7 @@ public class AccessControlListTag extends TagSupport {
return hasPermission;
}
@SuppressWarnings("unchecked")
private void initializeIfRequired() throws JspException {
if (applicationContext != null) {
return;

View File

@ -18,7 +18,6 @@ package org.springframework.security.taglibs.authz;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.jsp.JspException;
@ -27,9 +26,9 @@ import javax.servlet.jsp.tagext.TagSupport;
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.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.util.ExpressionEvaluationUtils;
@ -49,12 +48,10 @@ public class AuthorizeTag extends TagSupport {
//~ Methods ========================================================================================================
private Set authoritiesToRoles(Collection c) {
Set target = new HashSet();
for (Iterator iterator = c.iterator(); iterator.hasNext();) {
GrantedAuthority authority = (GrantedAuthority) iterator.next();
private Set<String> authoritiesToRoles(Collection<GrantedAuthority> c) {
Set<String> target = new HashSet<String>();
for (GrantedAuthority authority : c) {
if (null == authority.getAuthority()) {
throw new IllegalArgumentException(
"Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
@ -73,13 +70,13 @@ public class AuthorizeTag extends TagSupport {
return Tag.SKIP_BODY;
}
final Collection granted = getPrincipalAuthorities();
final Collection<GrantedAuthority> granted = getPrincipalAuthorities();
final String evaledIfNotGranted = ExpressionEvaluationUtils.evaluateString("ifNotGranted", ifNotGranted,
pageContext);
if ((null != evaledIfNotGranted) && !"".equals(evaledIfNotGranted)) {
Set grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfNotGranted));
Set<GrantedAuthority> grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfNotGranted));
if (!grantedCopy.isEmpty()) {
return Tag.SKIP_BODY;
@ -99,7 +96,7 @@ public class AuthorizeTag extends TagSupport {
pageContext);
if ((null != evaledIfAnyGranted) && !"".equals(evaledIfAnyGranted)) {
Set grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfAnyGranted));
Set<GrantedAuthority> grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfAnyGranted));
if (grantedCopy.isEmpty()) {
return Tag.SKIP_BODY;
@ -135,20 +132,9 @@ public class AuthorizeTag extends TagSupport {
return currentUser.getAuthorities();
}
private Set parseAuthoritiesString(String authorizationsString) {
final Set requiredAuthorities = new HashSet();
final String[] authorities = StringUtils.commaDelimitedListToStringArray(authorizationsString);
for (int i = 0; i < authorities.length; i++) {
String authority = authorities[i];
// Remove the role's whitespace characters without depending on JDK 1.4+
// Includes space, tab, new line, carriage return and form feed.
String role = authority.trim(); // trim, don't use spaces, as per SEC-378
role = StringUtils.deleteAny(role, "\t\n\r\f");
requiredAuthorities.add(new GrantedAuthorityImpl(role));
}
private Set<GrantedAuthority> parseAuthoritiesString(String authorizationsString) {
final Set<GrantedAuthority> requiredAuthorities = new HashSet<GrantedAuthority>();
requiredAuthorities.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(authorizationsString));
return requiredAuthorities;
}
@ -161,39 +147,31 @@ public class AuthorizeTag extends TagSupport {
* invalidating {@link Collection#retainAll(java.util.Collection)} results.</p>
* <p>
* <strong>CAVEAT</strong>: This method <strong>will not</strong> work if the granted authorities
* returns a <code>null</code> string as the return value of {@link
* org.springframework.security.core.GrantedAuthority#getAuthority()}.
* returns a <code>null</code> string as the return value of {@link GrantedAuthority#getAuthority()}.
* </p>
* <p>Reported by rawdave, on Fri Feb 04, 2005 2:11 pm in the Spring Security forum.</p>
*
* @param granted The authorities granted by the authentication. May be any implementation of {@link
* GrantedAuthority} that does <strong>not</strong> return <code>null</code> from {@link
* org.springframework.security.core.GrantedAuthority#getAuthority()}.
* GrantedAuthority#getAuthority()}.
* @param required A {@link Set} of {@link GrantedAuthorityImpl}s that have been built using ifAny, ifAll or
* ifNotGranted.
*
* @return A set containing only the common authorities between <var>granted</var> and <var>required</var>.
*
* @see <a href="http://forum.springframework.org/viewtopic.php?t=3367">authz:authorize ifNotGranted not behaving
* as expected</a> TODO: wrong article Url
*/
private Set retainAll(final Collection granted, final Set required) {
Set grantedRoles = authoritiesToRoles(granted);
Set requiredRoles = authoritiesToRoles(required);
private Set<GrantedAuthority> retainAll(final Collection<GrantedAuthority> granted, final Set<GrantedAuthority> required) {
Set<String> grantedRoles = authoritiesToRoles(granted);
Set<String> requiredRoles = authoritiesToRoles(required);
grantedRoles.retainAll(requiredRoles);
return rolesToAuthorities(grantedRoles, granted);
}
private Set rolesToAuthorities(Set grantedRoles, Collection granted) {
Set target = new HashSet();
for (Iterator iterator = grantedRoles.iterator(); iterator.hasNext();) {
String role = (String) iterator.next();
for (Iterator grantedIterator = granted.iterator(); grantedIterator.hasNext();) {
GrantedAuthority authority = (GrantedAuthority) grantedIterator.next();
private Set<GrantedAuthority> rolesToAuthorities(Set<String> grantedRoles, Collection<GrantedAuthority> granted) {
Set<GrantedAuthority> target = new HashSet<GrantedAuthority>();
for (String role : grantedRoles) {
for (GrantedAuthority authority : granted) {
if (authority.getAuthority().equals(role)) {
target.add(authority);

View File

@ -15,18 +15,17 @@
package org.springframework.security.taglibs.authz;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import junit.framework.TestCase;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
/**
* Tests {@link AuthenticationTag}.

View File

@ -78,7 +78,7 @@ public class AuthorizeTagTests extends TestCase {
}
public void testOutputsBodyWhenAllGranted() throws JspException {
authorizeTag.setIfAllGranted("ROLE SUPERVISOR,ROLE_TELLER");
authorizeTag.setIfAllGranted("ROLE SUPERVISOR, \nROLE_TELLER");
assertEquals("allows request - all required roles granted on principal", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
@ -102,7 +102,7 @@ public class AuthorizeTagTests extends TestCase {
}
public void testSkipsBodyWhenMissingAnAllGranted() throws JspException {
authorizeTag.setIfAllGranted("ROLE SUPERVISOR,ROLE_TELLER,ROLE_BANKER");
authorizeTag.setIfAllGranted("ROLE SUPERVISOR, ROLE_TELLER,\n\rROLE_BANKER");
assertEquals("prevents request - missing ROLE_BANKER on principal", Tag.SKIP_BODY, authorizeTag.doStartTag());
}

View File

@ -19,7 +19,6 @@ import junit.framework.TestCase;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

View File

@ -18,7 +18,6 @@ package org.springframework.security.web.util;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.savedrequest.SavedRequest;
/**

View File

@ -10,16 +10,13 @@ import javax.servlet.http.HttpServletRequest;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.MappableAttributesRetriever;
import org.springframework.security.core.authority.mapping.SimpleAttributes2GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.SimpleMappableAttributesRetriever;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.j2ee.J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.StringUtils;
/**
*

View File

@ -26,7 +26,7 @@ import org.springframework.security.web.session.HttpSessionDestroyedEvent;
*
* @author Ray Krueger
*/
public class MockApplicationListener implements ApplicationListener {
public class MockApplicationListener implements ApplicationListener<ApplicationEvent> {
//~ Instance fields ================================================================================================
private HttpSessionCreatedEvent createdEvent;