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

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,5 @@
<html>
<body>
Java implementation of security taglib.
</body>
</html>

View File

@@ -0,0 +1,5 @@
<html>
<body>
Provides security related taglibs that can be used in JSPs.
</body>
</html>

View File

@@ -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);
}

View File

@@ -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;
}
}
}

View File

@@ -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>