1
0
mirror of synced 2026-05-22 21:33:16 +00:00

SEC-674: Created new project modules for cas, captcha, acls and taglibs

This commit is contained in:
Luke Taylor
2008-02-19 20:30:53 +00:00
parent 59651f5214
commit 2dd9faabc0
149 changed files with 425 additions and 218 deletions
+49
View File
@@ -0,0 +1,49 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>spring-security-parent</artifactId>
<groupId>org.springframework.security</groupId>
<version>2.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<name>Spring Security - JSP Taglibs</name>
<version>2.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.0.6</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,234 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.NotFoundException;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalStrategy;
import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalStrategyImpl;
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.acls.sid.SidRetrievalStrategy;
import org.springframework.security.acls.sid.SidRetrievalStrategyImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.util.ExpressionEvaluationUtils;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.HashMap;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* An implementation of {@link Tag} that allows its body through if some authorizations are granted to the request's
* principal.
* <p>
* One or more comma separate numeric are specified via the <tt>hasPermission</tt> attribute.
* These permissions are then converted into {@link Permission} instances. These instances are then presented as an
* array to the {@link Acl#isGranted(Permission[], org.springframework.security.acls.sid.Sid[], boolean)} method.
* The {@link Sid} presented is determined by the {@link SidRetrievalStrategy}.
* <p>
* For this class to operate it must be able to access the application context via the
* <code>WebApplicationContextUtils</code> and locate an {@link AclService} and {@link SidRetrievalStrategy}.
* Application contexts must provide one and only one of these Java types.
*
* @author Ben Alex
* @version $Id$
*/
public class AccessControlListTag extends TagSupport {
//~ Static fields/initializers =====================================================================================
protected static final Log logger = LogFactory.getLog(AccessControlListTag.class);
//~ Instance fields ================================================================================================
private AclService aclService;
private ApplicationContext applicationContext;
private Object domainObject;
private ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy;
private SidRetrievalStrategy sidRetrievalStrategy;
private String hasPermission = "";
//~ Methods ========================================================================================================
public int doStartTag() throws JspException {
initializeIfRequired();
if ((null == hasPermission) || "".equals(hasPermission)) {
return Tag.SKIP_BODY;
}
final String evaledPermissionsString = ExpressionEvaluationUtils.evaluateString("hasPermission", hasPermission,
pageContext);
Permission[] requiredPermissions = null;
try {
requiredPermissions = parsePermissionsString(evaledPermissionsString);
} catch (NumberFormatException nfe) {
throw new JspException(nfe);
}
Object resolvedDomainObject = null;
if (domainObject instanceof String) {
resolvedDomainObject = ExpressionEvaluationUtils.evaluate("domainObject", (String) domainObject,
Object.class, pageContext);
} else {
resolvedDomainObject = domainObject;
}
if (resolvedDomainObject == null) {
if (logger.isDebugEnabled()) {
logger.debug("domainObject resolved to null, so including tag body");
}
// Of course they have access to a null object!
return Tag.EVAL_BODY_INCLUDE;
}
if (SecurityContextHolder.getContext().getAuthentication() == null) {
if (logger.isDebugEnabled()) {
logger.debug(
"SecurityContextHolder did not return a non-null Authentication object, so skipping tag body");
}
return Tag.SKIP_BODY;
}
Sid[] sids = sidRetrievalStrategy.getSids(SecurityContextHolder.getContext().getAuthentication());
ObjectIdentity oid = objectIdentityRetrievalStrategy.getObjectIdentity(resolvedDomainObject);
// Obtain aclEntrys applying to the current Authentication object
try {
Acl acl = aclService.readAclById(oid, sids);
if (acl.isGranted(requiredPermissions, sids, false)) {
return Tag.EVAL_BODY_INCLUDE;
} else {
return Tag.SKIP_BODY;
}
} catch (NotFoundException nfe) {
return Tag.SKIP_BODY;
}
}
/**
* Allows test cases to override where application context obtained from.
*
* @param pageContext so the <code>ServletContext</code> can be accessed as required by Spring's
* <code>WebApplicationContextUtils</code>
*
* @return the Spring application context (never <code>null</code>)
*/
protected ApplicationContext getContext(PageContext pageContext) {
ServletContext servletContext = pageContext.getServletContext();
return WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
}
public Object getDomainObject() {
return domainObject;
}
public String getHasPermission() {
return hasPermission;
}
private void initializeIfRequired() throws JspException {
if (applicationContext != null) {
return;
}
this.applicationContext = getContext(pageContext);
Map map = new HashMap();
ApplicationContext context = applicationContext;
while (context != null) {
map.putAll(context.getBeansOfType(AclService.class));
context = context.getParent();
}
if (map.size() != 1) {
throw new JspException(
"Found incorrect number of AclService instances in application context - you must have only have one!");
}
aclService = (AclService) map.values().iterator().next();
map = applicationContext.getBeansOfType(SidRetrievalStrategy.class);
if (map.size() == 0) {
sidRetrievalStrategy = new SidRetrievalStrategyImpl();
} else if (map.size() == 1) {
sidRetrievalStrategy = (SidRetrievalStrategy) map.values().iterator().next();
} else {
throw new JspException("Found incorrect number of SidRetrievalStrategy instances in application "
+ "context - you must have only have one!");
}
map = applicationContext.getBeansOfType(ObjectIdentityRetrievalStrategy.class);
if (map.size() == 0) {
objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
} else if (map.size() == 1) {
objectIdentityRetrievalStrategy = (ObjectIdentityRetrievalStrategy) map.values().iterator().next();
} else {
throw new JspException("Found incorrect number of ObjectIdentityRetrievalStrategy instances in "
+ "application context - you must have only have one!");
}
}
private Permission[] parsePermissionsString(String integersString)
throws NumberFormatException {
final Set permissions = new HashSet();
final StringTokenizer tokenizer;
tokenizer = new StringTokenizer(integersString, ",", false);
while (tokenizer.hasMoreTokens()) {
String integer = tokenizer.nextToken();
permissions.add(BasePermission.buildFromMask(new Integer(integer).intValue()));
}
return (Permission[]) permissions.toArray(new Permission[permissions.size()]);
}
public void setDomainObject(Object domainObject) {
this.domainObject = domainObject;
}
public void setHasPermission(String hasPermission) {
this.hasPermission = hasPermission;
}
}
@@ -0,0 +1,211 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import org.springframework.security.Authentication;
import org.springframework.security.acl.AclEntry;
import org.springframework.security.acl.AclManager;
import org.springframework.security.acl.basic.BasicAclEntry;
import org.springframework.security.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.util.ExpressionEvaluationUtils;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* An implementation of {@link javax.servlet.jsp.tagext.Tag} that allows its body through if some authorizations
* are granted to the request's principal.<P>Only works with permissions that are subclasses of {@link
* org.springframework.security.acl.basic.BasicAclEntry}.</p>
* <p>One or more comma separate integer permissions are specified via the <code>hasPermission</code> attribute.
* The tag will include its body if <b>any</b> of the integer permissions have been granted to the current
* <code>Authentication</code> (obtained from the <code>SecurityContextHolder</code>).</p>
* <p>For this class to operate it must be able to access the application context via the
* <code>WebApplicationContextUtils</code> and locate an {@link AclManager}. Application contexts have no need to have
* more than one <code>AclManager</code> (as a provider-based implementation can be used so that it locates a provider
* that is authoritative for the given domain object instance), so the first <code>AclManager</code> located will be
* used.</p>
*
* @author Ben Alex
* @version $Id$
*/
public class AclTag extends TagSupport {
//~ Static fields/initializers =====================================================================================
protected static final Log logger = LogFactory.getLog(AclTag.class);
//~ Instance fields ================================================================================================
private Object domainObject;
private String hasPermission = "";
//~ Methods ========================================================================================================
public int doStartTag() throws JspException {
if ((null == hasPermission) || "".equals(hasPermission)) {
return Tag.SKIP_BODY;
}
final String evaledPermissionsString = ExpressionEvaluationUtils.evaluateString("hasPermission", hasPermission,
pageContext);
Integer[] requiredIntegers = null;
try {
requiredIntegers = parseIntegersString(evaledPermissionsString);
} catch (NumberFormatException nfe) {
throw new JspException(nfe);
}
Object resolvedDomainObject = null;
if (domainObject instanceof String) {
resolvedDomainObject = ExpressionEvaluationUtils.evaluate("domainObject", (String) domainObject,
Object.class, pageContext);
} else {
resolvedDomainObject = domainObject;
}
if (resolvedDomainObject == null) {
if (logger.isDebugEnabled()) {
logger.debug("domainObject resolved to null, so including tag body");
}
// Of course they have access to a null object!
return Tag.EVAL_BODY_INCLUDE;
}
if (SecurityContextHolder.getContext().getAuthentication() == null) {
if (logger.isDebugEnabled()) {
logger.debug(
"SecurityContextHolder did not return a non-null Authentication object, so skipping tag body");
}
return Tag.SKIP_BODY;
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
ApplicationContext context = getContext(pageContext);
String[] beans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, AclManager.class, false, false);
if (beans.length == 0) {
throw new JspException("No AclManager would found the application context: " + context.toString());
}
AclManager aclManager = (AclManager) context.getBean(beans[0]);
// Obtain aclEntrys applying to the current Authentication object
AclEntry[] acls = aclManager.getAcls(resolvedDomainObject, auth);
if (logger.isDebugEnabled()) {
logger.debug("Authentication: '" + auth + "' has: " + ((acls == null) ? 0 : acls.length)
+ " AclEntrys for domain object: '" + resolvedDomainObject + "' from AclManager: '"
+ aclManager.toString() + "'");
}
if ((acls == null) || (acls.length == 0)) {
return Tag.SKIP_BODY;
}
for (int i = 0; i < acls.length; i++) {
// Locate processable AclEntrys
if (acls[i] instanceof BasicAclEntry) {
BasicAclEntry processableAcl = (BasicAclEntry) acls[i];
// See if principal has any of the required permissions
for (int y = 0; y < requiredIntegers.length; y++) {
if (processableAcl.isPermitted(requiredIntegers[y].intValue())) {
if (logger.isDebugEnabled()) {
logger.debug("Including tag body as found permission: " + requiredIntegers[y]
+ " due to AclEntry: '" + processableAcl + "'");
}
return Tag.EVAL_BODY_INCLUDE;
}
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("No permission, so skipping tag body");
}
return Tag.SKIP_BODY;
}
/**
* Allows test cases to override where application context obtained from.
*
* @param pageContext so the <code>ServletContext</code> can be accessed as required by Spring's
* <code>WebApplicationContextUtils</code>
*
* @return the Spring application context (never <code>null</code>)
*/
protected ApplicationContext getContext(PageContext pageContext) {
ServletContext servletContext = pageContext.getServletContext();
return WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
}
public Object getDomainObject() {
return domainObject;
}
public String getHasPermission() {
return hasPermission;
}
private Integer[] parseIntegersString(String integersString)
throws NumberFormatException {
final Set integers = new HashSet();
final StringTokenizer tokenizer;
tokenizer = new StringTokenizer(integersString, ",", false);
while (tokenizer.hasMoreTokens()) {
String integer = tokenizer.nextToken();
integers.add(new Integer(integer));
}
return (Integer[]) integers.toArray(new Integer[] {});
}
public void setDomainObject(Object domainObject) {
this.domainObject = domainObject;
}
public void setHasPermission(String hasPermission) {
this.hasPermission = hasPermission;
}
}
@@ -0,0 +1,135 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.web.util.TagUtils;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* An {@link javax.servlet.jsp.tagext.Tag} implementation that allows convenient access to the current
* <code>Authentication</code> object. The <tt>operation</tt> attribute
* <p>
* Whilst JSPs can access the <code>SecurityContext</code> directly, this tag avoids handling <code>null</code> conditions.
*
* @author Thomas Champagne
* @version $Id$
*/
public class AuthenticationTag extends TagSupport {
//~ Instance fields ================================================================================================
private String var;
private String property;
private int scope;
private boolean scopeSpecified;
//~ Methods ========================================================================================================
public AuthenticationTag() {
init();
}
// resets local state
private void init() {
var = null;
scopeSpecified = false;
scope = PageContext.PAGE_SCOPE;
}
public void setVar(String var) {
this.var = var;
}
public void setProperty(String operation) {
this.property = operation;
}
public void setScope(String scope) {
this.scope = TagUtils.getScope(scope);
this.scopeSpecified = true;
}
public int doStartTag() throws JspException {
return super.doStartTag();
}
public int doEndTag() throws JspException {
Object result = null;
// determine the value by...
if (property != null) {
if ((SecurityContextHolder.getContext() == null)
|| !(SecurityContextHolder.getContext() instanceof SecurityContext)
|| (SecurityContextHolder.getContext().getAuthentication() == null)) {
return Tag.EVAL_PAGE;
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth.getPrincipal() == null) {
return Tag.EVAL_PAGE;
} else {
try {
BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
result = wrapper.getPropertyValue(property);
} catch (BeansException e) {
throw new JspException(e);
}
}
}
if (var != null) {
/*
* Store the result, letting an IllegalArgumentException
* propagate back if the scope is invalid (e.g., if an attempt
* is made to store something in the session without any
* HttpSession existing).
*/
if (result != null) {
pageContext.setAttribute(var, result, scope);
} else {
if (scopeSpecified) {
pageContext.removeAttribute(var, scope);
} else {
pageContext.removeAttribute(var);
}
}
} else {
writeMessage(result.toString());
}
return EVAL_PAGE;
}
protected void writeMessage(String msg) throws JspException {
try {
pageContext.getOut().write(String.valueOf(msg));
} catch (IOException ioe) {
throw new JspException(ioe);
}
}
}
@@ -0,0 +1,225 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.util.ExpressionEvaluationUtils;
import java.util.Arrays;
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;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* An implementation of {@link javax.servlet.jsp.tagext.Tag} that allows it's body through if some authorizations
* are granted to the request's principal.
*
* @author Francois Beausoleil
* @version $Id$
*/
public class AuthorizeTag extends TagSupport {
//~ Instance fields ================================================================================================
private String ifAllGranted = "";
private String ifAnyGranted = "";
private String ifNotGranted = "";
//~ Methods ========================================================================================================
private Set authoritiesToRoles(Collection c) {
Set target = new HashSet();
for (Iterator iterator = c.iterator(); iterator.hasNext();) {
GrantedAuthority authority = (GrantedAuthority) iterator.next();
if (null == authority.getAuthority()) {
throw new IllegalArgumentException(
"Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
+ authority.toString());
}
target.add(authority.getAuthority());
}
return target;
}
public int doStartTag() throws JspException {
if (((null == ifAllGranted) || "".equals(ifAllGranted)) && ((null == ifAnyGranted) || "".equals(ifAnyGranted))
&& ((null == ifNotGranted) || "".equals(ifNotGranted))) {
return Tag.SKIP_BODY;
}
final Collection granted = getPrincipalAuthorities();
final String evaledIfNotGranted = ExpressionEvaluationUtils.evaluateString("ifNotGranted", ifNotGranted,
pageContext);
if ((null != evaledIfNotGranted) && !"".equals(evaledIfNotGranted)) {
Set grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfNotGranted));
if (!grantedCopy.isEmpty()) {
return Tag.SKIP_BODY;
}
}
final String evaledIfAllGranted = ExpressionEvaluationUtils.evaluateString("ifAllGranted", ifAllGranted,
pageContext);
if ((null != evaledIfAllGranted) && !"".equals(evaledIfAllGranted)) {
if (!granted.containsAll(parseAuthoritiesString(evaledIfAllGranted))) {
return Tag.SKIP_BODY;
}
}
final String evaledIfAnyGranted = ExpressionEvaluationUtils.evaluateString("ifAnyGranted", ifAnyGranted,
pageContext);
if ((null != evaledIfAnyGranted) && !"".equals(evaledIfAnyGranted)) {
Set grantedCopy = retainAll(granted, parseAuthoritiesString(evaledIfAnyGranted));
if (grantedCopy.isEmpty()) {
return Tag.SKIP_BODY;
}
}
return Tag.EVAL_BODY_INCLUDE;
}
public String getIfAllGranted() {
return ifAllGranted;
}
public String getIfAnyGranted() {
return ifAnyGranted;
}
public String getIfNotGranted() {
return ifNotGranted;
}
private Collection getPrincipalAuthorities() {
Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
if (null == currentUser) {
return Collections.EMPTY_LIST;
}
if ((null == currentUser.getAuthorities()) || (currentUser.getAuthorities().length < 1)) {
return Collections.EMPTY_LIST;
}
Collection granted = Arrays.asList(currentUser.getAuthorities());
return granted;
}
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));
}
return requiredAuthorities;
}
/**
* Find the common authorities between the current authentication's {@link GrantedAuthority} and the ones
* that have been specified in the tag's ifAny, ifNot or ifAllGranted attributes.<p>We need to manually
* iterate over both collections, because the granted authorities might not implement {@link
* Object#equals(Object)} and {@link Object#hashCode()} in the same way as {@link GrantedAuthorityImpl}, thereby
* 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.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.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);
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();
if (authority.getAuthority().equals(role)) {
target.add(authority);
break;
}
}
}
return target;
}
public void setIfAllGranted(String ifAllGranted) throws JspException {
this.ifAllGranted = ifAllGranted;
}
public void setIfAnyGranted(String ifAnyGranted) throws JspException {
this.ifAnyGranted = ifAnyGranted;
}
public void setIfNotGranted(String ifNotGranted) throws JspException {
this.ifNotGranted = ifNotGranted;
}
}
@@ -0,0 +1,5 @@
<html>
<body>
Java implementation of security taglib.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Provides security related taglibs that can be used in JSPs.
</body>
</html>
@@ -0,0 +1,102 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.velocity;
import org.springframework.security.Authentication;
import org.springframework.security.acl.AclManager;
import org.springframework.security.taglibs.authz.AclTag;
import org.springframework.security.taglibs.authz.AuthenticationTag;
import org.springframework.security.taglibs.authz.AuthorizeTag;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.context.ApplicationContext;
/**
* Wrapper the implementation of Spring Security JSP tag includes:
* {@link AuthenticationTag}, {@link AclTag}, {@link AuthorizeTag}
*
* @author Wang Qi
* @version $Id$
*/
public interface Authz {
//~ Methods ========================================================================================================
/**
* all the listed roles must be granted to return true, otherwise fasle;
*
* @param roles - comma separate GrantedAuthoritys
*
* @return granted (true|false)
*/
boolean allGranted(String roles);
/**
* any the listed roles must be granted to return true, otherwise fasle;
*
* @param roles - comma separate GrantedAuthoritys
*
* @return granted (true|false)
*/
boolean anyGranted(String roles);
/**
* set Spring application context which contains acegi related bean
*
* @return DOCUMENT ME!
*/
ApplicationContext getAppCtx();
/**
* return the principal's name, supports the various type of principals that can exist in the {@link
* Authentication} object, such as a String or {@link UserDetails} instance
*
* @return string representation of principal's name
*/
String getPrincipal();
/**
* return true if the principal holds either permission specified for the provided domain object<P>Only
* works with permissions that are subclasses of {@link org.springframework.security.acl.basic.AbstractBasicAclEntry}.</p>
* <p>For this class to operate it must be able to access the application context via the
* <code>WebApplicationContextUtils</code> and locate an {@link AclManager}.</p>
*
* @param domainObject - domain object need acl control
* @param permissions - comma separate integer permissions
*
* @return got acl permission (true|false)
*/
boolean hasPermission(Object domainObject, String permissions);
/**
* none the listed roles must be granted to return true, otherwise fasle;
*
* @param roles - comma separate GrantedAuthoritys
*
* @return granted (true|false)
*/
boolean noneGranted(String roles);
/**
* get Spring application context which contains acegi related bean
*
* @param appCtx DOCUMENT ME!
*/
void setAppCtx(ApplicationContext appCtx);
}
@@ -0,0 +1,212 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.velocity;
import org.springframework.security.acl.AclManager;
import org.springframework.security.taglibs.authz.AclTag;
import org.springframework.security.taglibs.authz.AuthenticationTag;
import org.springframework.security.taglibs.authz.AuthorizeTag;
import org.springframework.context.ApplicationContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
/**
* I decided to wrap several JSP tag in one class, so I have to using inner class to wrap these JSP tag. To using
* this class, you need to inject Spring Context via SetAppCtx() method. AclTag need Spring Context to get AclManger
* bean.
*/
public class AuthzImpl implements Authz {
//~ Static fields/initializers =====================================================================================
static final int ALL_GRANTED = 1;
static final int ANY_GRANTED = 2;
static final int NONE_GRANTED = 3;
//~ Instance fields ================================================================================================
private ApplicationContext appCtx;
//~ Methods ========================================================================================================
public boolean allGranted(String roles) {
return ifGranted(roles, ALL_GRANTED);
}
public boolean anyGranted(String roles) {
return ifGranted(roles, ANY_GRANTED);
}
public ApplicationContext getAppCtx() {
return appCtx;
}
/**
* implementation of AuthenticationTag
*
* @return DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
public String getPrincipal() {
MyAuthenticationTag authenticationTag = new MyAuthenticationTag();
authenticationTag.setProperty("username");
try {
authenticationTag.doStartTag();
} catch (JspException je) {
je.printStackTrace();
throw new IllegalArgumentException(je.getMessage());
}
return authenticationTag.getLastMessage();
}
/**
* implementation of AclTag
*
* @param domainObject DOCUMENT ME!
* @param permissions DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
public boolean hasPermission(Object domainObject, String permissions) {
MyAclTag aclTag = new MyAclTag();
aclTag.setPageContext(null);
aclTag.setContext(getAppCtx());
aclTag.setDomainObject(domainObject);
aclTag.setHasPermission(permissions);
int result = -1;
try {
result = aclTag.doStartTag();
} catch (JspException je) {
throw new IllegalArgumentException(je.getMessage());
}
if (Tag.EVAL_BODY_INCLUDE == result) {
return true;
} else {
return false;
}
}
/**
* implementation of AuthorizeTag
*
* @param roles DOCUMENT ME!
* @param grantType DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
private boolean ifGranted(String roles, int grantType) {
AuthorizeTag authorizeTag = new AuthorizeTag();
int result = -1;
try {
switch (grantType) {
case ALL_GRANTED:
authorizeTag.setIfAllGranted(roles);
break;
case ANY_GRANTED:
authorizeTag.setIfAnyGranted(roles);
break;
case NONE_GRANTED:
authorizeTag.setIfNotGranted(roles);
break;
default:
throw new IllegalArgumentException("invalid granted type : " + grantType + " role=" + roles);
}
result = authorizeTag.doStartTag();
} catch (JspException je) {
throw new IllegalArgumentException(je.getMessage());
}
if (Tag.EVAL_BODY_INCLUDE == result) {
return true;
} else {
return false;
}
}
public boolean noneGranted(String roles) {
return ifGranted(roles, NONE_GRANTED);
}
/**
* test case can use this class to mock application context with aclManager bean in it.
*
* @param appCtx DOCUMENT ME!
*/
public void setAppCtx(ApplicationContext appCtx) {
this.appCtx = appCtx;
}
//~ Inner Classes ==================================================================================================
/**
* AclTag need to access the application context via the <code> WebApplicationContextUtils</code> and
* locate an {@link AclManager}. WebApplicationContextUtils get application context via ServletContext. I decided
* to let the Authz provide the Spring application context.
*/
private class MyAclTag extends AclTag {
private static final long serialVersionUID = 6752340622125924108L;
ApplicationContext context;
protected ApplicationContext getContext(PageContext pageContext) {
return context;
}
protected void setContext(ApplicationContext context) {
this.context = context;
}
}
/**
* it must output somthing to JSP page, so have to override the writeMessage method to avoid JSP related
* operation. Get Idea from Acegi Test class.
*/
private class MyAuthenticationTag extends AuthenticationTag {
private static final long serialVersionUID = -1094246833893599161L;
String lastMessage = null;
public String getLastMessage() {
return lastMessage;
}
protected void writeMessage(String msg) throws JspException {
lastMessage = msg;
}
}
}
@@ -0,0 +1,154 @@
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>security</short-name>
<uri>http://www.springframework.org/security/tags</uri>
<description>
Spring Security Authorization Tag Library
$Id$
</description>
<tag>
<name>authorize</name>
<tag-class>org.springframework.security.taglibs.authz.AuthorizeTag</tag-class>
<description>
A simple tag to output or not the body of the tag if the principal
has or doesn't have certain authorities.
</description>
<attribute>
<name>ifNotGranted</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
A comma separated list of roles which the user must not have
for the body to be output.
</description>
</attribute>
<attribute>
<name>ifAllGranted</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
A comma separated list of roles which the user must all
possess for the body to be output.
</description>
</attribute>
<attribute>
<name>ifAnyGranted</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>
A comma separated list of roles, one of which the user must
possess for the body to be output.
</description>
</attribute>
</tag>
<tag>
<name>authentication</name>
<tag-class>org.springframework.security.taglibs.authz.AuthenticationTag</tag-class>
<description>
Allows access to the current Authentication object.
</description>
<attribute>
<name>property</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>
Property of the Authentication object which should be output. Supports nested
properties. For example if the principal object is an instance of UserDetails,
te property "principal.username" will return the username. Alternatively, using
"name" will call getName method on the Authentication object directly.
</description>
</attribute>
<attribute>
<name>var</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description>
Name of the exported scoped variable for the
exception thrown from a nested action. The type of the
scoped variable is the type of the exception thrown.
</description>
</attribute>
<attribute>
<name>scope</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description>
Scope for var.
</description>
</attribute>
</tag>
<tag>
<name>acl</name>
<tag-class>org.springframework.security.taglibs.authz.AclTag</tag-class>
<description>
Allows inclusion of a tag body if the current Authentication
has one of the specified permissions to the presented
domain object instance. This tag uses the first AclManager
it locates via
WebApplicationContextUtils.getRequiredWebApplicationContext(HttpServletContext).
</description>
<attribute>
<name>hasPermission</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>
A comma separated list of integers, each representing a
required bit mask permission from a subclass of
org.springframework.security.acl.basic.AbstractBasicAclEntry.
</description>
</attribute>
<attribute>
<name>domainObject</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>
The actual domain object instance for which permissions
are being evaluated.
</description>
</attribute>
</tag>
<tag>
<name>accesscontrollist</name>
<tag-class>org.springframework.security.taglibs.authz.AccessControlListTag</tag-class>
<description>
Allows inclusion of a tag body if the current Authentication
has one of the specified permissions to the presented
domain object instance.
</description>
<attribute>
<name>hasPermission</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>
A comma separated list of integers, each representing a
required bit mask permission from a subclass of
org.springframework.security.acl.basic.AbstractBasicAclEntry.
</description>
</attribute>
<attribute>
<name>domainObject</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>
The actual domain object instance for which permissions
are being evaluated.
</description>
</attribute>
</tag>
</taglib>
@@ -0,0 +1,182 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.util.InMemoryXmlApplicationContext;
import org.springframework.security.acl.AclEntry;
import org.springframework.security.acl.AclManager;
import org.springframework.security.acl.basic.SimpleAclEntry;
import org.springframework.security.acl.basic.AclObjectIdentity;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
/**
* Tests {@link AclTag}.
*
* @author Ben Alex
* @version $Id$
*/
public class AclTagTests extends TestCase {
//~ Instance fields ================================================================================================
private final MyAclTag aclTag = new MyAclTag();
//~ Methods ========================================================================================================
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testInclusionDeniedWhenAclManagerUnawareOfObject() throws JspException {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION).toString());
aclTag.setDomainObject(new Integer(54));
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
}
public void testInclusionDeniedWhenNoListOfPermissionsGiven() throws JspException {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission(null);
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
}
public void testInclusionDeniedWhenPrincipalDoesNotHoldAnyPermissions() throws JspException {
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ));
assertEquals(new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ),
aclTag.getHasPermission());
aclTag.setDomainObject("object1");
assertEquals("object1", aclTag.getDomainObject());
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
}
public void testInclusionDeniedWhenPrincipalDoesNotHoldRequiredPermissions() throws JspException {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.DELETE).toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
}
public void testInclusionDeniedWhenSecurityContextEmpty() throws JspException {
SecurityContextHolder.getContext().setAuthentication(null);
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION).toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
}
public void testInclusionPermittedWhenDomainObjectIsNull() throws JspException {
aclTag.setHasPermission(new Integer(SimpleAclEntry.READ).toString());
aclTag.setDomainObject(null);
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
}
public void testJspExceptionThrownIfHasPermissionNotValidFormat() throws JspException {
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission("0,5, 6"); // shouldn't be any space
try {
aclTag.doStartTag();
fail("Should have thrown JspException");
} catch (JspException expected) {
assertTrue(true);
}
}
public void testOperationWhenPrincipalHoldsPermissionOfMultipleList() throws JspException {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ));
aclTag.setDomainObject("object1");
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
}
public void testOperationWhenPrincipalHoldsPermissionOfSingleList() throws JspException {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
aclTag.setHasPermission(new Integer(SimpleAclEntry.READ).toString());
aclTag.setDomainObject("object1");
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
}
//~ Inner Classes ==================================================================================================
private class MockAclEntry implements AclEntry {
// just so AclTag iterates some different types of AclEntrys
}
private class MyAclTag extends AclTag {
protected ApplicationContext getContext(PageContext pageContext) {
StaticApplicationContext context = new StaticApplicationContext();
final AclEntry[] acls = new AclEntry[] {
new MockAclEntry(),
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.READ)
};
// Create an AclManager
AclManager aclManager = new AclManager() {
String object = "object1";
String principal = "rod";
public AclEntry[] getAcls(Object domainInstance) {
return domainInstance.equals(object) ? acls : null;
}
public AclEntry[] getAcls(Object domainInstance, Authentication authentication) {
return domainInstance.equals(object) && authentication.getPrincipal().equals(principal) ? acls : null;
}
};
// Register the AclManager into our ApplicationContext
context.getBeanFactory().registerSingleton("aclManager", aclManager);
return context;
}
}
private static class MockAclObjectIdentity implements AclObjectIdentity {
}
}
@@ -0,0 +1,126 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.userdetails.User;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
/**
* Tests {@link AuthenticationTag}.
*
* @author Ben Alex
* @version $Id$
*/
public class AuthenticationTagTests extends TestCase {
//~ Instance fields ================================================================================================
private final MyAuthenticationTag authenticationTag = new MyAuthenticationTag();
private final Authentication auth = new TestingAuthenticationToken(new User("rodUserDetails", "koala", true, true, true,
true, new GrantedAuthority[] {}), "koala", new GrantedAuthority[] {});
//~ Methods ========================================================================================================
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testOperationWhenPrincipalIsAUserDetailsInstance()throws JspException {
SecurityContextHolder.getContext().setAuthentication(auth);
authenticationTag.setProperty("name");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
assertEquals("rodUserDetails", authenticationTag.getLastMessage());
}
public void testOperationWhenPrincipalIsAString() throws JspException {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("rodAsString", "koala", new GrantedAuthority[] {}));
authenticationTag.setProperty("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
assertEquals("rodAsString", authenticationTag.getLastMessage());
}
public void testNestedPropertyIsReadCorrectly() throws JspException {
SecurityContextHolder.getContext().setAuthentication(auth);
authenticationTag.setProperty("principal.username");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
assertEquals("rodUserDetails", authenticationTag.getLastMessage());
}
public void testOperationWhenPrincipalIsNull() throws JspException {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(null, "koala", new GrantedAuthority[] {}));
authenticationTag.setProperty("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
}
public void testOperationWhenSecurityContextIsNull() throws Exception {
SecurityContextHolder.getContext().setAuthentication(null);
authenticationTag.setProperty("principal");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
assertEquals(null, authenticationTag.getLastMessage());
}
public void testSkipsBodyIfNullOrEmptyOperation() throws Exception {
authenticationTag.setProperty("");
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
}
public void testThrowsExceptionForUnrecognisedProperty() {
SecurityContextHolder.getContext().setAuthentication(auth);
authenticationTag.setProperty("qsq");
try {
authenticationTag.doStartTag();
authenticationTag.doEndTag();
fail("Should have throwns JspException");
} catch (JspException expected) {
}
}
//~ Inner Classes ==================================================================================================
private class MyAuthenticationTag extends AuthenticationTag {
String lastMessage = null;
public String getLastMessage() {
return lastMessage;
}
protected void writeMessage(String msg) throws JspException {
lastMessage = msg;
}
}
}
@@ -0,0 +1,98 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
/**
* DOCUMENT ME!
*
* @author Francois Beausoleil
* @version $Id$
*/
public class AuthorizeTagAttributeTests extends TestCase {
//~ Instance fields ================================================================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private TestingAuthenticationToken currentUser;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_SUPERVISOR"), new GrantedAuthorityImpl("ROLE_RESTRICTED"),
});
SecurityContextHolder.getContext().setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testAssertsIfAllGrantedSecond() throws JspException {
authorizeTag.setIfAllGranted("ROLE_SUPERVISOR,ROLE_SUPERTELLER");
authorizeTag.setIfAnyGranted("ROLE_RESTRICTED");
assertEquals("prevents request - principal is missing ROLE_SUPERTELLER", Tag.SKIP_BODY,
authorizeTag.doStartTag());
}
public void testAssertsIfAnyGrantedLast() throws JspException {
authorizeTag.setIfAnyGranted("ROLE_BANKER");
assertEquals("prevents request - principal is missing ROLE_BANKER", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testAssertsIfNotGrantedFirst() throws JspException {
authorizeTag.setIfNotGranted("ROLE_RESTRICTED");
authorizeTag.setIfAllGranted("ROLE_SUPERVISOR,ROLE_RESTRICTED");
authorizeTag.setIfAnyGranted("ROLE_SUPERVISOR");
assertEquals("prevents request - principal has ROLE_RESTRICTED", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testAssertsIfNotGrantedIgnoresWhitespaceInAttribute()
throws JspException {
authorizeTag.setIfAnyGranted("\tROLE_SUPERVISOR \t, \r\n\t ROLE_TELLER ");
assertEquals("allows request - principal has ROLE_SUPERVISOR", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag());
}
public void testIfAllGrantedIgnoresWhitespaceInAttribute()
throws JspException {
authorizeTag.setIfAllGranted("\nROLE_SUPERVISOR\t,ROLE_RESTRICTED\t\n\r ");
assertEquals("allows request - principal has ROLE_RESTRICTED " + "and ROLE_SUPERVISOR", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
public void testIfNotGrantedIgnoresWhitespaceInAttribute()
throws JspException {
authorizeTag.setIfNotGranted(" \t ROLE_TELLER \r");
assertEquals("allows request - principal does not have ROLE_TELLER", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
}
@@ -0,0 +1,91 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
/**
* DOCUMENT ME!
*
* @author Francois Beausoleil
* @version $Id$
*/
public class AuthorizeTagCustomGrantedAuthorityTests extends TestCase {
//~ Instance fields ================================================================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private TestingAuthenticationToken currentUser;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {new CustomGrantedAuthority("ROLE_TELLER")});
SecurityContextHolder.getContext().setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testAllowsRequestWhenCustomAuthorityPresentsCorrectRole()
throws JspException {
authorizeTag.setIfAnyGranted("ROLE_TELLER");
assertEquals("authorized - ROLE_TELLER in both sets", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag());
}
public void testRejectsRequestWhenCustomAuthorityReturnsNull()
throws JspException {
authorizeTag.setIfAnyGranted("ROLE_TELLER");
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {new CustomGrantedAuthority(null)}));
try {
authorizeTag.doStartTag();
fail("Failed to reject GrantedAuthority with NULL getAuthority()");
} catch (IllegalArgumentException expected) {
assertTrue("expected", true);
}
}
//~ Inner Classes ==================================================================================================
private static class CustomGrantedAuthority implements GrantedAuthority {
private final String authority;
public CustomGrantedAuthority(String authority) {
this.authority = authority;
}
public String getAuthority() {
return authority;
}
}
}
@@ -0,0 +1,83 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.mock.web.MockPageContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
/**
* Test case to implement commons-el expression language expansion.
*/
public class AuthorizeTagExpressionLanguageTests extends TestCase {
//~ Instance fields ================================================================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private MockPageContext pageContext;
private TestingAuthenticationToken currentUser;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
pageContext = new MockPageContext();
authorizeTag.setPageContext(pageContext);
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"),});
SecurityContextHolder.getContext().setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testAllGrantedUsesExpressionLanguageWhenExpressionIsEL() throws JspException {
pageContext.setAttribute("authority", "ROLE_TELLER");
authorizeTag.setIfAllGranted("${authority}");
assertEquals("allows body - authority var contains ROLE_TELLER", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
public void testAnyGrantedUsesExpressionLanguageWhenExpressionIsEL() throws JspException {
pageContext.setAttribute("authority", "ROLE_TELLER");
authorizeTag.setIfAnyGranted("${authority}");
assertEquals("allows body - authority var contains ROLE_TELLER", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
public void testNotGrantedUsesExpressionLanguageWhenExpressionIsEL() throws JspException {
pageContext.setAttribute("authority", "ROLE_TELLER");
authorizeTag.setIfNotGranted("${authority}");
assertEquals("allows body - authority var contains ROLE_TELLER", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
}
@@ -0,0 +1,113 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
/**
* DOCUMENT ME!
*
* @author Francois Beausoleil
* @version $Id$
*/
public class AuthorizeTagTests extends TestCase {
//~ Instance fields ================================================================================================
private final AuthorizeTag authorizeTag = new AuthorizeTag();
private TestingAuthenticationToken currentUser;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE SUPERVISOR"), new GrantedAuthorityImpl("ROLE_TELLER"),
});
SecurityContextHolder.getContext().setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testAlwaysReturnsUnauthorizedIfNoUserFound() throws JspException {
SecurityContextHolder.getContext().setAuthentication(null);
authorizeTag.setIfAllGranted("ROLE_TELLER");
assertEquals("prevents request - no principal in Context", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testDefaultsToNotOutputtingBodyWhenNoRequiredAuthorities() throws JspException {
assertEquals("", authorizeTag.getIfAllGranted());
assertEquals("", authorizeTag.getIfAnyGranted());
assertEquals("", authorizeTag.getIfNotGranted());
assertEquals("prevents body output - no authorities granted", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testOutputsBodyIfOneRolePresent() throws JspException {
authorizeTag.setIfAnyGranted("ROLE_TELLER");
assertEquals("authorized - ROLE_TELLER in both sets", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag());
}
public void testOutputsBodyWhenAllGranted() throws JspException {
authorizeTag.setIfAllGranted("ROLE SUPERVISOR,ROLE_TELLER");
assertEquals("allows request - all required roles granted on principal", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
public void testOutputsBodyWhenNotGrantedSatisfied() throws JspException {
authorizeTag.setIfNotGranted("ROLE_BANKER");
assertEquals("allows request - principal doesn't have ROLE_BANKER", Tag.EVAL_BODY_INCLUDE,
authorizeTag.doStartTag());
}
public void testPreventsBodyOutputIfNoSecurityContext() throws JspException {
SecurityContextHolder.getContext().setAuthentication(null);
authorizeTag.setIfAnyGranted("ROLE_BANKER");
assertEquals("prevents output - no context defined", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testSkipsBodyIfNoAnyRolePresent() throws JspException {
authorizeTag.setIfAnyGranted("ROLE_BANKER");
assertEquals("unauthorized - ROLE_BANKER not in granted authorities", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testSkipsBodyWhenMissingAnAllGranted() throws JspException {
authorizeTag.setIfAllGranted("ROLE SUPERVISOR,ROLE_TELLER,ROLE_BANKER");
assertEquals("prevents request - missing ROLE_BANKER on principal", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
public void testSkipsBodyWhenNotGrantedUnsatisfied() throws JspException {
authorizeTag.setIfNotGranted("ROLE_TELLER");
assertEquals("prevents request - principal has ROLE_TELLER", Tag.SKIP_BODY, authorizeTag.doStartTag());
}
}
@@ -0,0 +1,95 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.velocity;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import javax.servlet.jsp.JspException;
/**
* DOCUMENT ME!
*/
public class AuthzImplAttributeTest extends TestCase {
//~ Instance fields ================================================================================================
private final Authz authz = new AuthzImpl();
private TestingAuthenticationToken currentUser;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_SUPERVISOR"), new GrantedAuthorityImpl("ROLE_RESTRICTED"),
});
SecurityContextHolder.getContext().setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testAssertsIfAllGrantedSecond() {
boolean r1 = authz.allGranted("ROLE_SUPERVISOR,ROLE_SUPERTELLER");
boolean r2 = authz.anyGranted("ROLE_RESTRICTED");
//prevents request - principal is missing ROLE_SUPERTELLE
assertFalse(r1 && r2);
}
public void testAssertsIfAnyGrantedLast() {
boolean r2 = authz.anyGranted("ROLE_BANKER");
// prevents request - principal is missing ROLE_BANKER
assertFalse(r2);
}
public void testAssertsIfNotGrantedFirst() {
boolean r1 = authz.allGranted("ROLE_SUPERVISOR,ROLE_RESTRICTED");
boolean r2 = authz.noneGranted("ROLE_RESTRICTED");
boolean r3 = authz.anyGranted("ROLE_SUPERVISOR");
//prevents request - principal has ROLE_RESTRICTED
assertFalse(r1 && r2 && r3);
}
public void testAssertsIfNotGrantedIgnoresWhitespaceInAttribute() {
//allows request - principal has ROLE_SUPERVISOR
assertTrue(authz.anyGranted("\tROLE_SUPERVISOR \t, \r\n\t ROLE_TELLER "));
}
public void testIfAllGrantedIgnoresWhitespaceInAttribute() {
//allows request - principal has ROLE_RESTRICTED and ROLE_SUPERVISOR
assertTrue(authz.allGranted("\nROLE_SUPERVISOR\t,ROLE_RESTRICTED\t\n\r "));
}
public void testIfNotGrantedIgnoresWhitespaceInAttribute()
throws JspException {
//prevents request - principal does not have ROLE_TELLER
assertFalse(authz.allGranted(" \t ROLE_TELLER \r"));
}
}
@@ -0,0 +1,104 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.velocity;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
/**
* DOCUMENT ME!
*/
public class AuthzImplAuthorizeTagTest extends TestCase {
//~ Instance fields ================================================================================================
private Authz authz = new AuthzImpl();
private TestingAuthenticationToken currentUser;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
currentUser = new TestingAuthenticationToken("abc", "123",
new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_SUPERVISOR"), new GrantedAuthorityImpl("ROLE_TELLER"),
});
SecurityContextHolder.getContext().setAuthentication(currentUser);
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testAlwaysReturnsUnauthorizedIfNoUserFound() {
SecurityContextHolder.getContext().setAuthentication(null);
//prevents request - no principal in Context
assertFalse(authz.allGranted("ROLE_TELLER"));
}
public void testDefaultsToNotOutputtingBodyWhenNoRequiredAuthorities() {
//prevents body output - no authorities granted
assertFalse(authz.allGranted(""));
assertFalse(authz.anyGranted(""));
assertFalse(authz.noneGranted(""));
}
public void testOutputsBodyIfOneRolePresent() {
//authorized - ROLE_TELLER in both sets
assertTrue(authz.anyGranted("ROLE_TELLER"));
}
public void testOutputsBodyWhenAllGranted() {
// allows request - all required roles granted on principal
assertTrue(authz.allGranted("ROLE_SUPERVISOR,ROLE_TELLER"));
}
public void testOutputsBodyWhenNotGrantedSatisfied() {
// allows request - principal doesn't have ROLE_BANKER
assertTrue(authz.noneGranted("ROLE_BANKER"));
}
public void testPreventsBodyOutputIfNoSecureContext() {
SecurityContextHolder.getContext().setAuthentication(null);
// prevents output - no context defined
assertFalse(authz.anyGranted("ROLE_BANKER"));
}
public void testSkipsBodyIfNoAnyRolePresent() {
// unauthorized - ROLE_BANKER not in granted authorities
assertFalse(authz.anyGranted("ROLE_BANKER"));
}
public void testSkipsBodyWhenMissingAnAllGranted() {
// prevents request - missing ROLE_BANKER on principal
assertFalse(authz.allGranted("ROLE_SUPERVISOR,ROLE_TELLER,ROLE_BANKER"));
}
public void testSkipsBodyWhenNotGrantedUnsatisfied() {
// prevents request - principal has ROLE_TELLER
assertFalse(authz.noneGranted("ROLE_TELLER"));
}
}
@@ -0,0 +1,246 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.velocity;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.acl.AclEntry;
import org.springframework.security.acl.AclManager;
import org.springframework.security.acl.basic.SimpleAclEntry;
import org.springframework.security.acl.basic.AclObjectIdentity;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.userdetails.User;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
public class AuthzImplTest extends TestCase {
//~ Instance fields ================================================================================================
private Authz authz = new AuthzImpl();
private ConfigurableApplicationContext ctx;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
super.setUp();
ctx = new StaticApplicationContext();
final AclEntry[] acls = new AclEntry[] {new MockAclEntry(),
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.READ)
};
// Create an AclManager
AclManager aclManager = new AclManager() {
String object = "object1";
String principal = "rod";
public AclEntry[] getAcls(Object domainInstance) {
return domainInstance.equals(object) ? acls : null;
}
public AclEntry[] getAcls(Object domainInstance, Authentication authentication) {
return domainInstance.equals(object) && authentication.getPrincipal().equals(principal) ? acls : null;
}
};
// Register the AclManager into our ApplicationContext
ctx.getBeanFactory().registerSingleton("aclManager", aclManager);
}
protected void tearDown() throws Exception {
ctx.close();
}
public void testIllegalArgumentExceptionThrownIfHasPermissionNotValidFormat() {
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
String permissions = "0,5, 6"; // shouldn't be any space
try {
authz.hasPermission(null, permissions);
} catch (IllegalArgumentException iae) {
assertTrue(true);
}
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testInclusionDeniedWhenAclManagerUnawareOfObject() {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
boolean result = authz.hasPermission(new Integer(54), new Long(SimpleAclEntry.ADMINISTRATION).toString());
assertFalse(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testInclusionDeniedWhenNoListOfPermissionsGiven() {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
boolean result = authz.hasPermission("object1", null);
assertFalse(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testInclusionDeniedWhenPrincipalDoesNotHoldAnyPermissions() {
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
String permissions = new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ);
boolean result = authz.hasPermission("object1", permissions);
assertFalse(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testInclusionDeniedWhenPrincipalDoesNotHoldRequiredPermissions() {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
String permissions = new Integer(SimpleAclEntry.DELETE).toString();
boolean result = authz.hasPermission("object1", permissions);
assertFalse(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testInclusionDeniedWhenSecurityContextEmpty() {
SecurityContextHolder.getContext().setAuthentication(null);
authz.setAppCtx(ctx);
String permissions = new Long(SimpleAclEntry.ADMINISTRATION).toString();
boolean result = authz.hasPermission("object1", permissions);
assertFalse(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testInclusionPermittedWhenDomainObjectIsNull() {
authz.setAppCtx(ctx);
String permissions = new Integer(SimpleAclEntry.READ).toString();
boolean result = authz.hasPermission(null, permissions);
assertTrue(result);
}
public void testOperationWhenPrincipalHoldsPermissionOfMultipleList() {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
String permissions = new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ);
boolean result = authz.hasPermission("object1", permissions);
assertTrue(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
public void testOperationWhenPrincipalHoldsPermissionOfSingleList() {
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
authz.setAppCtx(ctx);
String permissions = new Integer(SimpleAclEntry.READ).toString();
boolean result = authz.hasPermission("object1", permissions);
assertTrue(result);
SecurityContextHolder.getContext().setAuthentication(null);
}
/*
* Test method for 'com.alibaba.exodus2.web.common.security.pulltool.AuthzImpl.getPrincipal()'
*/
public void testOperationWhenPrincipalIsAString() {
Authentication auth = new TestingAuthenticationToken("rodAsString", "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
assertEquals("rodAsString", authz.getPrincipal());
}
public void testOperationWhenPrincipalIsAUserDetailsInstance() {
Authentication auth = new TestingAuthenticationToken(new User("rodUserDetails", "koala", true, true, true,
true, new GrantedAuthority[] {}), "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
assertEquals("rodUserDetails", authz.getPrincipal());
}
public void testOperationWhenPrincipalIsNull() {
Authentication auth = new TestingAuthenticationToken(null, "koala", new GrantedAuthority[] {});
SecurityContextHolder.getContext().setAuthentication(auth);
assertNull(authz.getPrincipal());
}
public void testOperationWhenSecurityContextIsNull() {
SecurityContextHolder.getContext().setAuthentication(null);
assertEquals(null, authz.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(null);
}
//~ Inner Classes ==================================================================================================
private class MockAclEntry implements AclEntry {
private static final long serialVersionUID = 1L;
// just so AclTag iterates some different types of AclEntrys
}
private static class MockAclObjectIdentity implements AclObjectIdentity {
}
}