Reformatting.

This commit is contained in:
Luke Taylor 2010-11-30 00:29:39 +00:00
parent 9b29dcb8bf
commit ca679e1479
3 changed files with 288 additions and 295 deletions

View File

@ -210,7 +210,7 @@ public class JaasAuthenticationProvider extends AbstractJaasAuthenticationProvid
* @param ase The excetion that caused the authentication failure * @param ase The excetion that caused the authentication failure
*/ */
protected void publishFailureEvent(UsernamePasswordAuthenticationToken token, AuthenticationException ase) { protected void publishFailureEvent(UsernamePasswordAuthenticationToken token, AuthenticationException ase) {
// exists for passivity (the superclass does a null check before publishing) // exists for passivity (the superclass does a null check before publishing)
getApplicationEventPublisher().publishEvent(new JaasAuthenticationFailedEvent(token, ase)); getApplicationEventPublisher().publishEvent(new JaasAuthenticationFailedEvent(token, ase));
} }

View File

@ -48,289 +48,285 @@ import org.springframework.web.context.support.WebApplicationContextUtils;
* A base class for an <authorize> tag that is independent of the tag rendering technology (JSP, Facelets). * A base class for an <authorize> tag that is independent of the tag rendering technology (JSP, Facelets).
* It treats tag attributes as simple strings rather than strings that may contain expressions with the * It treats tag attributes as simple strings rather than strings that may contain expressions with the
* exception of the "access" attribute, which is always expected to contain a Spring EL expression. * exception of the "access" attribute, which is always expected to contain a Spring EL expression.
* * <p/>
* Subclasses are expected to extract tag attribute values from the specific rendering technology, evaluate * Subclasses are expected to extract tag attribute values from the specific rendering technology, evaluate
* them as expressions if necessary, and set the String-based attributes of this class. * them as expressions if necessary, and set the String-based attributes of this class.
* *
* @author Francois Beausoleil * @author Francois Beausoleil
* @author Luke Taylor * @author Luke Taylor
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*
* @since 3.1.0 * @since 3.1.0
*/ */
public abstract class AbstractAuthorizeTag { public abstract class AbstractAuthorizeTag {
private String access; private String access;
private String url; private String url;
private String method; private String method;
private String ifAllGranted; private String ifAllGranted;
private String ifAnyGranted; private String ifAnyGranted;
private String ifNotGranted; private String ifNotGranted;
/** /**
* This method allows subclasses to provide a way to access the ServletRequest according to the rendering * This method allows subclasses to provide a way to access the ServletRequest according to the rendering
* technology. * technology.
*/ */
protected abstract ServletRequest getRequest(); protected abstract ServletRequest getRequest();
/** /**
* This method allows subclasses to provide a way to access the ServletResponse according to the rendering * This method allows subclasses to provide a way to access the ServletResponse according to the rendering
* technology. * technology.
*/ */
protected abstract ServletResponse getResponse(); protected abstract ServletResponse getResponse();
/** /**
* This method allows subclasses to provide a way to access the ServletContext according to the rendering * This method allows subclasses to provide a way to access the ServletContext according to the rendering
* technology. * technology.
*/ */
protected abstract ServletContext getServletContext(); protected abstract ServletContext getServletContext();
/** /**
* Make an authorization decision by considering all &lt;authorize&gt; tag attributes. The following are valid * Make an authorization decision by considering all &lt;authorize&gt; tag attributes. The following are valid
* combinations of attributes: * combinations of attributes:
* <ul> * <ul>
* <li>access</li> * <li>access</li>
* <li>url, method</li> * <li>url, method</li>
* <li>ifAllGranted, ifAnyGranted, ifNotGranted</li> * <li>ifAllGranted, ifAnyGranted, ifNotGranted</li>
* </ul> * </ul>
* The above combinations are mutually exclusive and evaluated in the given order. * The above combinations are mutually exclusive and evaluated in the given order.
* *
* @return the result of the authorization decision * @return the result of the authorization decision
* * @throws IOException
* @throws IOException */
*/ public boolean authorize() throws IOException {
public boolean authorize() throws IOException { boolean isAuthorized = false;
boolean isAuthorized = false;
if (StringUtils.hasText(getAccess())) { if (StringUtils.hasText(getAccess())) {
isAuthorized = authorizeUsingAccessExpression(); isAuthorized = authorizeUsingAccessExpression();
} else if (StringUtils.hasText(getUrl())) { } else if (StringUtils.hasText(getUrl())) {
isAuthorized = authorizeUsingUrlCheck(); isAuthorized = authorizeUsingUrlCheck();
} else { } else {
isAuthorized = authorizeUsingGrantedAuthorities(); isAuthorized = authorizeUsingGrantedAuthorities();
} }
return isAuthorized; return isAuthorized;
} }
/** /**
* Make an authorization decision by considering ifAllGranted, ifAnyGranted, and ifNotGranted. All 3 or any * Make an authorization decision by considering ifAllGranted, ifAnyGranted, and ifNotGranted. All 3 or any
* combination can be provided. All provided attributes must evaluate to true. * combination can be provided. All provided attributes must evaluate to true.
* *
* @return the result of the authorization decision * @return the result of the authorization decision
*/ */
public boolean authorizeUsingGrantedAuthorities() { public boolean authorizeUsingGrantedAuthorities() {
boolean hasTextAllGranted = StringUtils.hasText(getIfAllGranted()); boolean hasTextAllGranted = StringUtils.hasText(getIfAllGranted());
boolean hasTextAnyGranted = StringUtils.hasText(getIfAnyGranted()); boolean hasTextAnyGranted = StringUtils.hasText(getIfAnyGranted());
boolean hasTextNotGranted = StringUtils.hasText(getIfNotGranted()); boolean hasTextNotGranted = StringUtils.hasText(getIfNotGranted());
if ((!hasTextAllGranted) && (!hasTextAnyGranted) && (!hasTextNotGranted)) { if ((!hasTextAllGranted) && (!hasTextAnyGranted) && (!hasTextNotGranted)) {
return false; return false;
} }
final Collection<? extends GrantedAuthority> granted = getPrincipalAuthorities(); final Collection<? extends GrantedAuthority> granted = getPrincipalAuthorities();
if (hasTextAllGranted) { if (hasTextAllGranted) {
if (!granted.containsAll(toAuthorities(getIfAllGranted()))) { if (!granted.containsAll(toAuthorities(getIfAllGranted()))) {
return false; return false;
} }
} }
if (hasTextAnyGranted) { if (hasTextAnyGranted) {
Set<GrantedAuthority> grantedCopy = retainAll(granted, toAuthorities(getIfAnyGranted())); Set<GrantedAuthority> grantedCopy = retainAll(granted, toAuthorities(getIfAnyGranted()));
if (grantedCopy.isEmpty()) { if (grantedCopy.isEmpty()) {
return false; return false;
} }
} }
if (hasTextNotGranted) { if (hasTextNotGranted) {
Set<GrantedAuthority> grantedCopy = retainAll(granted, toAuthorities(getIfNotGranted())); Set<GrantedAuthority> grantedCopy = retainAll(granted, toAuthorities(getIfNotGranted()));
if (!grantedCopy.isEmpty()) { if (!grantedCopy.isEmpty()) {
return false; return false;
} }
} }
return true; return true;
} }
/** /**
* Make an authorization decision based on a Spring EL expression. See the "Expression-Based Access Control" chapter * Make an authorization decision based on a Spring EL expression. See the "Expression-Based Access Control" chapter
* in Spring Security for details on what expressions can be used. * in Spring Security for details on what expressions can be used.
* *
* @return the result of the authorization decision * @return the result of the authorization decision
* * @throws IOException
* @throws IOException */
*/ public boolean authorizeUsingAccessExpression() throws IOException {
public boolean authorizeUsingAccessExpression() throws IOException { Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); if (currentUser == null) {
if (currentUser == null) { return false;
return false; }
}
SecurityExpressionHandler<FilterInvocation> handler = getExpressionHandler(); SecurityExpressionHandler<FilterInvocation> handler = getExpressionHandler();
Expression accessExpression; Expression accessExpression;
try { try {
accessExpression = handler.getExpressionParser().parseExpression(getAccess()); accessExpression = handler.getExpressionParser().parseExpression(getAccess());
} catch (ParseException e) { } catch (ParseException e) {
IOException ioException = new IOException(); IOException ioException = new IOException();
ioException.initCause(e); ioException.initCause(e);
throw ioException; throw ioException;
} }
FilterInvocation f = new FilterInvocation(getRequest(), getResponse(), new FilterChain() { FilterInvocation f = new FilterInvocation(getRequest(), getResponse(), new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
}); });
return ExpressionUtils.evaluateAsBoolean(accessExpression, handler.createEvaluationContext(currentUser, f)); return ExpressionUtils.evaluateAsBoolean(accessExpression, handler.createEvaluationContext(currentUser, f));
} }
/** /**
* Make an authorization decision based on the URL and HTTP method attributes. True is returned if the user is * Make an authorization decision based on the URL and HTTP method attributes. True is returned if the user is
* allowed to access the given URL as defined. * allowed to access the given URL as defined.
* *
* @return the result of the authorization decision * @return the result of the authorization decision
* * @throws IOException
* @throws IOException */
*/ public boolean authorizeUsingUrlCheck() throws IOException {
public boolean authorizeUsingUrlCheck() throws IOException { String contextPath = ((HttpServletRequest) getRequest()).getContextPath();
String contextPath = ((HttpServletRequest) getRequest()).getContextPath(); Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); return getPrivilegeEvaluator().isAllowed(contextPath, getUrl(), getMethod(), currentUser);
return getPrivilegeEvaluator().isAllowed(contextPath, getUrl(), getMethod(), currentUser); }
}
public String getAccess() { public String getAccess() {
return access; return access;
} }
public void setAccess(String access) { public void setAccess(String access) {
this.access = access; this.access = access;
} }
public String getUrl() { public String getUrl() {
return url; return url;
} }
public void setUrl(String url) { public void setUrl(String url) {
this.url = url; this.url = url;
} }
public String getMethod() { public String getMethod() {
return method; return method;
} }
public void setMethod(String method) { public void setMethod(String method) {
this.method = (method != null) ? method.toUpperCase() : null; this.method = (method != null) ? method.toUpperCase() : null;
} }
public String getIfAllGranted() { public String getIfAllGranted() {
return ifAllGranted; return ifAllGranted;
} }
public void setIfAllGranted(String ifAllGranted) { public void setIfAllGranted(String ifAllGranted) {
this.ifAllGranted = ifAllGranted; this.ifAllGranted = ifAllGranted;
} }
public String getIfAnyGranted() { public String getIfAnyGranted() {
return ifAnyGranted; return ifAnyGranted;
} }
public void setIfAnyGranted(String ifAnyGranted) { public void setIfAnyGranted(String ifAnyGranted) {
this.ifAnyGranted = ifAnyGranted; this.ifAnyGranted = ifAnyGranted;
} }
public String getIfNotGranted() { public String getIfNotGranted() {
return ifNotGranted; return ifNotGranted;
} }
public void setIfNotGranted(String ifNotGranted) { public void setIfNotGranted(String ifNotGranted) {
this.ifNotGranted = ifNotGranted; this.ifNotGranted = ifNotGranted;
} }
/*------------- Private helper methods -----------------*/ /*------------- Private helper methods -----------------*/
private Collection<? extends GrantedAuthority> getPrincipalAuthorities() { private Collection<? extends GrantedAuthority> getPrincipalAuthorities() {
Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
if (null == currentUser) { if (null == currentUser) {
return Collections.emptyList(); return Collections.emptyList();
} }
return currentUser.getAuthorities(); return currentUser.getAuthorities();
} }
private Set<GrantedAuthority> toAuthorities(String authorizations) { private Set<GrantedAuthority> toAuthorities(String authorizations) {
final Set<GrantedAuthority> requiredAuthorities = new HashSet<GrantedAuthority>(); final Set<GrantedAuthority> requiredAuthorities = new HashSet<GrantedAuthority>();
requiredAuthorities.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(authorizations)); requiredAuthorities.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(authorizations));
return requiredAuthorities; return requiredAuthorities;
} }
private Set<GrantedAuthority> retainAll(final Collection<? extends GrantedAuthority> granted, private Set<GrantedAuthority> retainAll(final Collection<? extends GrantedAuthority> granted,
final Set<GrantedAuthority> required) { final Set<GrantedAuthority> required) {
Set<String> grantedRoles = authoritiesToRoles(granted); Set<String> grantedRoles = authoritiesToRoles(granted);
Set<String> requiredRoles = authoritiesToRoles(required); Set<String> requiredRoles = authoritiesToRoles(required);
grantedRoles.retainAll(requiredRoles); grantedRoles.retainAll(requiredRoles);
return rolesToAuthorities(grantedRoles, granted); return rolesToAuthorities(grantedRoles, granted);
} }
private Set<String> authoritiesToRoles(Collection<? extends GrantedAuthority> c) { private Set<String> authoritiesToRoles(Collection<? extends GrantedAuthority> c) {
Set<String> target = new HashSet<String>(); Set<String> target = new HashSet<String>();
for (GrantedAuthority authority : c) { for (GrantedAuthority authority : c) {
if (null == authority.getAuthority()) { if (null == authority.getAuthority()) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process " "Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
+ authority.toString()); + authority.toString());
} }
target.add(authority.getAuthority()); target.add(authority.getAuthority());
} }
return target; return target;
} }
private Set<GrantedAuthority> rolesToAuthorities(Set<String> grantedRoles, Collection<? extends GrantedAuthority> granted) { private Set<GrantedAuthority> rolesToAuthorities(Set<String> grantedRoles, Collection<? extends GrantedAuthority> granted) {
Set<GrantedAuthority> target = new HashSet<GrantedAuthority>(); Set<GrantedAuthority> target = new HashSet<GrantedAuthority>();
for (String role : grantedRoles) { for (String role : grantedRoles) {
for (GrantedAuthority authority : granted) { for (GrantedAuthority authority : granted) {
if (authority.getAuthority().equals(role)) { if (authority.getAuthority().equals(role)) {
target.add(authority); target.add(authority);
break; break;
} }
} }
} }
return target; return target;
} }
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException { private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = WebApplicationContextUtils ApplicationContext appContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext()); .getRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext Map<String, SecurityExpressionHandler> handlers = appContext
.getBeansOfType(SecurityExpressionHandler.class); .getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler h : handlers.values()) { for (SecurityExpressionHandler h : handlers.values()) {
if (FilterInvocation.class.equals(GenericTypeResolver.resolveTypeArgument(h.getClass(), if (FilterInvocation.class.equals(GenericTypeResolver.resolveTypeArgument(h.getClass(),
SecurityExpressionHandler.class))) { SecurityExpressionHandler.class))) {
return h; return h;
} }
} }
throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application " throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application "
+ "context. There must be at least one in order to support expressions in JSP 'authorize' tags."); + "context. There must be at least one in order to support expressions in JSP 'authorize' tags.");
} }
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException { private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class); Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.size() == 0) { if (wipes.size() == 0) {
throw new IOException( throw new IOException(
"No visible WebInvocationPrivilegeEvaluator instance could be found in the application " "No visible WebInvocationPrivilegeEvaluator instance could be found in the application "
+ "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags."); + "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags.");
} }
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0]; return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
} }
} }

View File

@ -12,106 +12,103 @@ import javax.servlet.jsp.tagext.Tag;
import org.springframework.web.util.ExpressionEvaluationUtils; import org.springframework.web.util.ExpressionEvaluationUtils;
/** /**
* A JSP {@link Tag} implementation of {@link AbstractAuthorizeTag}. * A JSP {@link Tag} implementation of {@link AbstractAuthorizeTag}.
* *
* @since 3.1.0
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*
* @see AbstractAuthorizeTag * @see AbstractAuthorizeTag
* @since 3.1.0
*/ */
public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag { public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag {
private Tag parent; private Tag parent;
protected PageContext pageContext; protected PageContext pageContext;
protected String id; protected String id;
private String var; private String var;
/** /**
* Invokes the base class {@link AbstractAuthorizeTag#authorize()} method to * Invokes the base class {@link AbstractAuthorizeTag#authorize()} method to
* decide if the body of the tag should be skipped or not. * decide if the body of the tag should be skipped or not.
* *
* @return {@link Tag#SKIP_BODY} or {@link Tag#EVAL_BODY_INCLUDE} * @return {@link Tag#SKIP_BODY} or {@link Tag#EVAL_BODY_INCLUDE}
*/ */
public int doStartTag() throws JspException { public int doStartTag() throws JspException {
try { try {
setIfNotGranted(ExpressionEvaluationUtils.evaluateString("ifNotGranted", getIfNotGranted(), pageContext)); setIfNotGranted(ExpressionEvaluationUtils.evaluateString("ifNotGranted", getIfNotGranted(), pageContext));
setIfAllGranted(ExpressionEvaluationUtils.evaluateString("ifAllGranted", getIfAllGranted(), pageContext)); setIfAllGranted(ExpressionEvaluationUtils.evaluateString("ifAllGranted", getIfAllGranted(), pageContext));
setIfAnyGranted(ExpressionEvaluationUtils.evaluateString("ifAnyGranted", getIfAnyGranted(), pageContext)); setIfAnyGranted(ExpressionEvaluationUtils.evaluateString("ifAnyGranted", getIfAnyGranted(), pageContext));
int result = super.authorize() ? Tag.EVAL_BODY_INCLUDE : Tag.SKIP_BODY;
if (var != null) { int result = super.authorize() ? Tag.EVAL_BODY_INCLUDE : Tag.SKIP_BODY;
pageContext.setAttribute(var, Boolean.valueOf(result == EVAL_BODY_INCLUDE), PageContext.PAGE_SCOPE);
} if (var != null) {
pageContext.setAttribute(var, Boolean.valueOf(result == EVAL_BODY_INCLUDE), PageContext.PAGE_SCOPE);
return result; }
} catch (IOException e) { return result;
throw new JspException(e);
} } catch (IOException e) {
} throw new JspException(e);
}
}
/** /**
* Default processing of the end tag returning EVAL_PAGE. * Default processing of the end tag returning EVAL_PAGE.
* *
* @return EVAL_PAGE * @return EVAL_PAGE
*
* @see Tag#doEndTag() * @see Tag#doEndTag()
*/ */
public int doEndTag() { public int doEndTag() {
return EVAL_PAGE; return EVAL_PAGE;
} }
public String getId() { public String getId() {
return id; return id;
} }
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
public Tag getParent() { public Tag getParent() {
return parent; return parent;
} }
public void setParent(Tag parent) { public void setParent(Tag parent) {
this.parent = parent; this.parent = parent;
} }
public String getVar() {
return var;
}
public void setVar(String var) { public String getVar() {
this.var = var; return var;
} }
public void release() { public void setVar(String var) {
parent = null; this.var = var;
id = null; }
}
public void setPageContext(PageContext pageContext) { public void release() {
this.pageContext = pageContext; parent = null;
} id = null;
}
@Override public void setPageContext(PageContext pageContext) {
protected ServletRequest getRequest() { this.pageContext = pageContext;
return pageContext.getRequest(); }
}
@Override @Override
protected ServletResponse getResponse() { protected ServletRequest getRequest() {
return pageContext.getResponse(); return pageContext.getRequest();
} }
@Override @Override
protected ServletContext getServletContext() { protected ServletResponse getResponse() {
return pageContext.getServletContext(); return pageContext.getResponse();
} }
@Override
protected ServletContext getServletContext() {
return pageContext.getServletContext();
}
} }