org.springframework.util.SecurityUtils Maven / Gradle / Ivy
package org.springframework.util;
import java.io.IOException;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ParseException;
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SecurityUtils {
private final static Log logger = LogFactory.getLog(SecurityUtils.class);
public static final FilterChain DUMMY_CHAIN = new FilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
throw new UnsupportedOperationException();
}
};
public static boolean evaluate(Authentication authentication, String expression, HttpServletRequest request, HttpServletResponse response) {
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
SecurityExpressionHandler webSecurityExpressionHandler = getSecurityExpressionHandler(webApplicationContext);
if (webSecurityExpressionHandler == null) {
return false;
}
EvaluationContext ctx = webSecurityExpressionHandler.createEvaluationContext(authentication, new FilterInvocation(request, response, DUMMY_CHAIN));
try {
return ExpressionUtils.evaluateAsBoolean(webSecurityExpressionHandler.getExpressionParser().parseExpression(expression), ctx);
}
catch (ParseException e) {
if (logger.isWarnEnabled()) {
logger.warn(e, e);
}
return false;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static SecurityExpressionHandler getSecurityExpressionHandler(ApplicationContext applicationContext) {
Map expressionHandlers = applicationContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler handler : expressionHandlers.values()) {
if (FilterInvocation.class.equals(GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) {
return handler;
}
}
return null;
}
}