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

Reformat code using spring-javaformat

Run `./gradlew format` to reformat all java files.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-10 16:39:17 -05:00
committed by Rob Winch
parent 81d9c6cac5
commit b7fc18262d
2487 changed files with 41506 additions and 46548 deletions
@@ -29,6 +29,7 @@ import javax.servlet.jsp.tagext.Tag;
* @author Luke Taylor
*/
public final class TagLibConfig {
static Log logger = LogFactory.getLog("spring-security-taglibs");
static final boolean DISABLE_UI_SECURITY;
@@ -53,7 +54,6 @@ public final class TagLibConfig {
/**
* Returns EVAL_BODY_INCLUDE if the authorized flag is true or UI security has been
* disabled. Otherwise returns SKIP_BODY.
*
* @param authorized whether the user is authorized to see the content or not
*/
public static int evalOrSkip(boolean authorized) {
@@ -75,4 +75,5 @@ public final class TagLibConfig {
public static String getSecuredUiSuffix() {
return SECURED_UI_SUFFIX;
}
}
@@ -55,8 +55,11 @@ import org.springframework.util.StringUtils;
* @since 3.1.0
*/
public abstract class AbstractAuthorizeTag {
private String access;
private String url;
private String method = "GET";
/**
@@ -85,7 +88,6 @@ public abstract class AbstractAuthorizeTag {
* <li>url, method</li>
* </ul>
* The above combinations are mutually exclusive and evaluated in the given order.
*
* @return the result of the authorization decision
* @throws IOException
*/
@@ -112,7 +114,6 @@ public abstract class AbstractAuthorizeTag {
* 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.
*
* @return the result of the authorization decision
* @throws IOException
*/
@@ -134,37 +135,30 @@ public abstract class AbstractAuthorizeTag {
throw ioException;
}
return ExpressionUtils.evaluateAsBoolean(accessExpression,
createExpressionEvaluationContext(handler));
return ExpressionUtils.evaluateAsBoolean(accessExpression, createExpressionEvaluationContext(handler));
}
/**
* Allows the {@code EvaluationContext} to be customized for variable lookup etc.
*/
protected EvaluationContext createExpressionEvaluationContext(
SecurityExpressionHandler<FilterInvocation> handler) {
FilterInvocation f = new FilterInvocation(getRequest(), getResponse(),
(request, response) -> {
throw new UnsupportedOperationException();
});
protected EvaluationContext createExpressionEvaluationContext(SecurityExpressionHandler<FilterInvocation> handler) {
FilterInvocation f = new FilterInvocation(getRequest(), getResponse(), (request, response) -> {
throw new UnsupportedOperationException();
});
return handler.createEvaluationContext(SecurityContextHolder.getContext()
.getAuthentication(), f);
return handler.createEvaluationContext(SecurityContextHolder.getContext().getAuthentication(), f);
}
/**
* 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.
*
* @return the result of the authorization decision
* @throws IOException
*/
public boolean authorizeUsingUrlCheck() throws IOException {
String contextPath = ((HttpServletRequest) getRequest()).getContextPath();
Authentication currentUser = SecurityContextHolder.getContext()
.getAuthentication();
return getPrivilegeEvaluator().isAllowed(contextPath, getUrl(), getMethod(),
currentUser);
Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
return getPrivilegeEvaluator().isAllowed(contextPath, getUrl(), getMethod(), currentUser);
}
public String getAccess() {
@@ -194,22 +188,20 @@ public abstract class AbstractAuthorizeTag {
/*------------- Private helper methods -----------------*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler()
throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext
.getBeansOfType(SecurityExpressionHandler.class);
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler h : handlers.values()) {
if (FilterInvocation.class.equals(GenericTypeResolver.resolveTypeArgument(
h.getClass(), SecurityExpressionHandler.class))) {
if (FilterInvocation.class
.equals(GenericTypeResolver.resolveTypeArgument(h.getClass(), SecurityExpressionHandler.class))) {
return h;
}
}
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.");
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.");
}
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
@@ -219,9 +211,9 @@ public abstract class AbstractAuthorizeTag {
return privEvaluatorFromRequest;
}
ApplicationContext ctx = SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx
.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
ApplicationContext ctx = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.size() == 0) {
throw new IOException(
@@ -231,4 +223,5 @@ public abstract class AbstractAuthorizeTag {
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
}
}
@@ -34,7 +34,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.taglibs.TagLibConfig;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
/**
* An implementation of {@link Tag} that allows its body through if all authorizations are
* granted to the request's principal.
@@ -53,6 +52,7 @@ import org.springframework.security.web.context.support.SecurityWebApplicationCo
* @author Rob Winch
*/
public class AccessControlListTag extends TagSupport {
// ~ Static fields/initializers
// =====================================================================================
@@ -62,9 +62,13 @@ public class AccessControlListTag extends TagSupport {
// ================================================================================================
private ApplicationContext applicationContext;
private Object domainObject;
private PermissionEvaluator permissionEvaluator;
private String hasPermission = "";
private String var;
// ~ Methods
@@ -86,11 +90,11 @@ public class AccessControlListTag extends TagSupport {
return evalBody();
}
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder did not return a non-null Authentication object, so skipping tag body");
logger.debug(
"SecurityContextHolder did not return a non-null Authentication object, so skipping tag body");
}
return skipBody();
@@ -98,8 +102,7 @@ public class AccessControlListTag extends TagSupport {
List<Object> requiredPermissions = parseHasPermission(hasPermission);
for (Object requiredPermission : requiredPermissions) {
if (!permissionEvaluator.hasPermission(authentication, domainObject,
requiredPermission)) {
if (!permissionEvaluator.hasPermission(authentication, domainObject, requiredPermission)) {
return skipBody();
}
}
@@ -138,10 +141,8 @@ public class AccessControlListTag extends TagSupport {
/**
* 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) {
@@ -183,8 +184,8 @@ public class AccessControlListTag extends TagSupport {
return map.values().iterator().next();
}
throw new JspException("Found incorrect number of " + type.getSimpleName()
+ " instances in " + "application context - you must have only have one!");
throw new JspException("Found incorrect number of " + type.getSimpleName() + " instances in "
+ "application context - you must have only have one!");
}
public void setDomainObject(Object domainObject) {
@@ -198,4 +199,5 @@ public class AccessControlListTag extends TagSupport {
public void setVar(String var) {
this.var = var;
}
}
@@ -47,9 +47,13 @@ public class AuthenticationTag extends TagSupport {
// ================================================================================================
private String var;
private String property;
private int scope;
private boolean scopeSpecified;
private boolean htmlEscape = true;
// ~ Methods
@@ -160,4 +164,5 @@ public class AuthenticationTag extends TagSupport {
protected boolean isHtmlEscape() {
return htmlEscape;
}
}
@@ -61,7 +61,6 @@ public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag {
/**
* Invokes the base class {@link AbstractAuthorizeTag#authorize()} method to decide if
* the body of the tag should be skipped or not.
*
* @return {@link Tag#SKIP_BODY} or {@link Tag#EVAL_BODY_INCLUDE}
*/
public int doStartTag() throws JspException {
@@ -85,15 +84,12 @@ public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag {
}
@Override
protected EvaluationContext createExpressionEvaluationContext(
SecurityExpressionHandler<FilterInvocation> handler) {
return new PageContextVariableLookupEvaluationContext(
super.createExpressionEvaluationContext(handler));
protected EvaluationContext createExpressionEvaluationContext(SecurityExpressionHandler<FilterInvocation> handler) {
return new PageContextVariableLookupEvaluationContext(super.createExpressionEvaluationContext(handler));
}
/**
* Default processing of the end tag returning EVAL_PAGE.
*
* @return EVAL_PAGE
* @see Tag#doEndTag()
*/
@@ -158,8 +154,7 @@ public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag {
return pageContext.getServletContext();
}
private final class PageContextVariableLookupEvaluationContext implements
EvaluationContext {
private final class PageContextVariableLookupEvaluationContext implements EvaluationContext {
private EvaluationContext delegate;
@@ -215,6 +210,7 @@ public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag {
}
return result;
}
}
}
@@ -17,4 +17,3 @@
* JSP Security tag library implementation.
*/
package org.springframework.security.taglibs.authz;
@@ -33,8 +33,7 @@ abstract class AbstractCsrfTag extends TagSupport {
@Override
public int doEndTag() throws JspException {
CsrfToken token = (CsrfToken) this.pageContext.getRequest().getAttribute(
CsrfToken.class.getName());
CsrfToken token = (CsrfToken) this.pageContext.getRequest().getAttribute(CsrfToken.class.getName());
if (token != null) {
try {
this.pageContext.getOut().write(this.handleToken(token));
@@ -48,4 +47,5 @@ abstract class AbstractCsrfTag extends TagSupport {
}
protected abstract String handleToken(CsrfToken token);
}
@@ -29,7 +29,7 @@ public class CsrfInputTag extends AbstractCsrfTag {
@Override
public String handleToken(CsrfToken token) {
return "<input type=\"hidden\" name=\"" + token.getParameterName()
+ "\" value=\"" + token.getToken() + "\" />";
return "<input type=\"hidden\" name=\"" + token.getParameterName() + "\" value=\"" + token.getToken() + "\" />";
}
}
@@ -29,9 +29,9 @@ public class CsrfMetaTagsTag extends AbstractCsrfTag {
@Override
public String handleToken(CsrfToken token) {
return "<meta name=\"_csrf_parameter\" content=\"" + token.getParameterName()
+ "\" />" + "<meta name=\"_csrf_header\" content=\""
+ token.getHeaderName() + "\" />" + "<meta name=\"_csrf\" content=\""
+ token.getToken() + "\" />";
return "<meta name=\"_csrf_parameter\" content=\"" + token.getParameterName() + "\" />"
+ "<meta name=\"_csrf_header\" content=\"" + token.getHeaderName() + "\" />"
+ "<meta name=\"_csrf\" content=\"" + token.getToken() + "\" />";
}
}
@@ -17,4 +17,3 @@
* Security related tag libraries that can be used in JSPs and templates.
*/
package org.springframework.security.taglibs;
@@ -27,9 +27,9 @@ import static org.assertj.core.api.Assertions.assertThat;
public class TldTests {
//SEC-2324
// SEC-2324
@Test
public void testTldVersionIsCorrect() throws Exception{
public void testTldVersionIsCorrect() throws Exception {
String SPRING_SECURITY_VERSION = "springSecurityVersion";
String version = System.getProperty(SPRING_SECURITY_VERSION);
@@ -45,5 +45,4 @@ public class TldTests {
assertThat(version).startsWith(tlibVersion);
}
}
@@ -45,14 +45,17 @@ import org.springframework.security.web.access.expression.DefaultWebSecurityExpr
import org.springframework.web.context.WebApplicationContext;
/**
*
* @author Rob Winch
*
*/
public class AbstractAuthorizeTagTests {
private AbstractAuthorizeTag tag;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockServletContext servletContext;
@Before
@@ -73,8 +76,7 @@ public class AbstractAuthorizeTagTests {
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
tag.setUrl(uri);
request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE,
expected);
request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
tag.authorizeUsingUrlCheck();
@@ -87,7 +89,8 @@ public class AbstractAuthorizeTagTests {
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
tag.setUrl(uri);
WebApplicationContext wac = mock(WebApplicationContext.class);
when(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)).thenReturn(Collections.singletonMap("wipe", expected));
when(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class))
.thenReturn(Collections.singletonMap("wipe", expected));
servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
tag.authorizeUsingUrlCheck();
@@ -102,7 +105,8 @@ public class AbstractAuthorizeTagTests {
DefaultWebSecurityExpressionHandler expected = new DefaultWebSecurityExpressionHandler();
tag.setAccess("permitAll");
WebApplicationContext wac = mock(WebApplicationContext.class);
when(wac.getBeansOfType(SecurityExpressionHandler.class)).thenReturn(Collections.<String, SecurityExpressionHandler>singletonMap("wipe", expected));
when(wac.getBeansOfType(SecurityExpressionHandler.class))
.thenReturn(Collections.<String, SecurityExpressionHandler>singletonMap("wipe", expected));
servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
assertThat(tag.authorize()).isTrue();
@@ -124,5 +128,7 @@ public class AbstractAuthorizeTagTests {
protected ServletContext getServletContext() {
return servletContext;
}
}
}
@@ -34,16 +34,19 @@ import javax.servlet.jsp.tagext.Tag;
import java.util.*;
/**
*
* @author Luke Taylor
* @author Rob Winch
* @since 3.0
*/
@SuppressWarnings("unchecked")
public class AccessControlListTagTests {
AccessControlListTag tag;
PermissionEvaluator pe;
MockPageContext pageContext;
Authentication bob = new TestingAuthenticationToken("bob", "bobspass", "A");
@Before
@@ -60,10 +63,8 @@ public class AccessControlListTagTests {
when(ctx.getBeansOfType(PermissionEvaluator.class)).thenReturn(beanMap);
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
pageContext = new MockPageContext(servletCtx, new MockHttpServletRequest(),
new MockHttpServletResponse());
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
pageContext = new MockPageContext(servletCtx, new MockHttpServletRequest(), new MockHttpServletResponse());
tag.setPageContext(pageContext);
}
@@ -179,4 +180,5 @@ public class AccessControlListTagTests {
assertThat(tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat((Boolean) pageContext.getAttribute("allowed")).isFalse();
}
}
@@ -35,13 +35,15 @@ import org.springframework.security.core.userdetails.User;
* @author Ben Alex
*/
public class AuthenticationTagTests {
// ~ Instance fields
// ================================================================================================
private final MyAuthenticationTag authenticationTag = new MyAuthenticationTag();
private final Authentication auth = new TestingAuthenticationToken(new User(
"rodUserDetails", "koala", true, true, true, true,
AuthorityUtils.NO_AUTHORITIES), "koala", AuthorityUtils.NO_AUTHORITIES);
private final Authentication auth = new TestingAuthenticationToken(
new User("rodUserDetails", "koala", true, true, true, true, AuthorityUtils.NO_AUTHORITIES), "koala",
AuthorityUtils.NO_AUTHORITIES);
// ~ Methods
// ========================================================================================================
@@ -64,8 +66,7 @@ public class AuthenticationTagTests {
@Test
public void testOperationWhenPrincipalIsAString() throws JspException {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("rodAsString", "koala",
AuthorityUtils.NO_AUTHORITIES));
new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES));
authenticationTag.setProperty("principal");
assertThat(authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
@@ -85,9 +86,8 @@ public class AuthenticationTagTests {
@Test
public void testOperationWhenPrincipalIsNull() throws JspException {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(null, "koala",
AuthorityUtils.NO_AUTHORITIES));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(null, "koala", AuthorityUtils.NO_AUTHORITIES));
authenticationTag.setProperty("principal");
assertThat(authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
@@ -127,8 +127,7 @@ public class AuthenticationTagTests {
@Test
public void htmlEscapingIsUsedByDefault() throws Exception {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("<>& ", ""));
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("<>& ", ""));
authenticationTag.setProperty("name");
authenticationTag.doStartTag();
authenticationTag.doEndTag();
@@ -137,8 +136,7 @@ public class AuthenticationTagTests {
@Test
public void settingHtmlEscapeToFalsePreventsEscaping() throws Exception {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("<>& ", ""));
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("<>& ", ""));
authenticationTag.setProperty("name");
authenticationTag.setHtmlEscape("false");
authenticationTag.doStartTag();
@@ -150,6 +148,7 @@ public class AuthenticationTagTests {
// ==================================================================================================
private class MyAuthenticationTag extends AuthenticationTag {
String lastMessage = null;
public String getLastMessage() {
@@ -159,5 +158,7 @@ public class AuthenticationTagTests {
protected void writeMessage(String msg) {
lastMessage = msg;
}
}
}
@@ -48,15 +48,19 @@ import org.springframework.web.context.support.StaticWebApplicationContext;
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthorizeTagTests {
// ~ Instance fields
// ================================================================================================
@Mock
private PermissionEvaluator permissionEvaluator;
private JspAuthorizeTag authorizeTag;
private MockHttpServletRequest request = new MockHttpServletRequest();
private final TestingAuthenticationToken currentUser = new TestingAuthenticationToken(
"abc", "123", "ROLE SUPERVISOR", "ROLE_TELLER");
private final TestingAuthenticationToken currentUser = new TestingAuthenticationToken("abc", "123",
"ROLE SUPERVISOR", "ROLE_TELLER");
// ~ Methods
// ========================================================================================================
@@ -70,15 +74,12 @@ public class AuthorizeTagTests {
.rootBeanDefinition(DefaultWebSecurityExpressionHandler.class);
webExpressionHandler.addPropertyValue("permissionEvaluator", permissionEvaluator);
ctx.registerBeanDefinition("expressionHandler",
webExpressionHandler.getBeanDefinition());
ctx.registerBeanDefinition("expressionHandler", webExpressionHandler.getBeanDefinition());
ctx.registerSingleton("wipe", MockWebInvocationPrivilegeEvaluator.class);
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
authorizeTag = new JspAuthorizeTag();
authorizeTag.setPageContext(new MockPageContext(servletCtx, request,
new MockHttpServletResponse()));
authorizeTag.setPageContext(new MockPageContext(servletCtx, request, new MockHttpServletResponse()));
}
@After
@@ -92,10 +93,8 @@ public class AuthorizeTagTests {
public void taglibsDocumentationHasPermissionOr() throws Exception {
Object domain = new Object();
request.setAttribute("domain", domain);
authorizeTag
.setAccess("hasPermission(#domain,'read') or hasPermission(#domain,'write')");
when(permissionEvaluator.hasPermission(eq(currentUser), eq(domain), anyString()))
.thenReturn(true);
authorizeTag.setAccess("hasPermission(#domain,'read') or hasPermission(#domain,'write')");
when(permissionEvaluator.hasPermission(eq(currentUser), eq(domain), anyString())).thenReturn(true);
assertThat(authorizeTag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
}
@@ -154,16 +153,16 @@ public class AuthorizeTagTests {
assertThat(authorizeTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
}
public static class MockWebInvocationPrivilegeEvaluator implements
WebInvocationPrivilegeEvaluator {
public static class MockWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
public boolean isAllowed(String uri, Authentication authentication) {
return "/allowed".equals(uri);
}
public boolean isAllowed(String contextPath, String uri, String method,
Authentication authentication) {
public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) {
return "/allowed".equals(uri) && (method == null || "GET".equals(method));
}
}
}
@@ -37,7 +37,9 @@ import static org.assertj.core.api.Assertions.*;
public class AbstractCsrfTagTests {
public MockTag tag;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
@@ -45,8 +47,7 @@ public class AbstractCsrfTagTests {
MockServletContext servletContext = new MockServletContext();
this.request = new MockHttpServletRequest(servletContext);
this.response = new MockHttpServletResponse();
MockPageContext pageContext = new MockPageContext(servletContext, this.request,
this.response);
MockPageContext pageContext = new MockPageContext(servletContext, this.request, this.response);
this.tag = new MockTag();
this.tag.setPageContext(pageContext);
}
@@ -59,15 +60,14 @@ public class AbstractCsrfTagTests {
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE);
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("");
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.")
.isEqualTo("");
}
@Test
public void hasCsrfRendersReturnedValue() throws JspException,
UnsupportedEncodingException {
public void hasCsrfRendersReturnedValue() throws JspException, UnsupportedEncodingException {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf",
"abc123def456ghi789");
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
this.request.setAttribute(CsrfToken.class.getName(), token);
this.tag.handleReturn = "fooBarBazQux";
@@ -75,16 +75,15 @@ public class AbstractCsrfTagTests {
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE);
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("fooBarBazQux");
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.")
.isEqualTo("fooBarBazQux");
assertThat(this.tag.token).as("The token is not correct.").isSameAs(token);
}
@Test
public void hasCsrfRendersDifferentValue() throws JspException,
UnsupportedEncodingException {
public void hasCsrfRendersDifferentValue() throws JspException, UnsupportedEncodingException {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf",
"abc123def456ghi789");
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
this.request.setAttribute(CsrfToken.class.getName(), token);
this.tag.handleReturn = "<input type=\"hidden\" />";
@@ -92,13 +91,15 @@ public class AbstractCsrfTagTests {
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE);
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("<input type=\"hidden\" />");
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.")
.isEqualTo("<input type=\"hidden\" />");
assertThat(this.tag.token).as("The token is not correct.").isSameAs(token);
}
private static class MockTag extends AbstractCsrfTag {
private CsrfToken token;
private String handleReturn;
@Override
@@ -106,5 +107,7 @@ public class AbstractCsrfTagTests {
this.token = token;
return this.handleReturn;
}
}
}
@@ -36,24 +36,24 @@ public class CsrfInputTagTests {
@Test
public void handleTokenReturnsHiddenInput() {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf",
"abc123def456ghi789");
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(
value).withFailMessage("The output is not correct.").isEqualTo("<input type=\"hidden\" name=\"_csrf\" value=\"abc123def456ghi789\" />");
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<input type=\"hidden\" name=\"_csrf\" value=\"abc123def456ghi789\" />");
}
@Test
public void handleTokenReturnsHiddenInputDifferentTokenValue() {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "csrfParameter",
"fooBarBazQux");
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "csrfParameter", "fooBarBazQux");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<input type=\"hidden\" name=\"csrfParameter\" value=\"fooBarBazQux\" />");
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<input type=\"hidden\" name=\"csrfParameter\" value=\"fooBarBazQux\" />");
}
}
@@ -36,27 +36,28 @@ public class CsrfMetaTagsTagTests {
@Test
public void handleTokenRendersTags() {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf",
"abc123def456ghi789");
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"
+ "<meta name=\"_csrf_header\" content=\"X-Csrf-Token\" />"
+ "<meta name=\"_csrf\" content=\"abc123def456ghi789\" />");
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"
+ "<meta name=\"_csrf_header\" content=\"X-Csrf-Token\" />"
+ "<meta name=\"_csrf\" content=\"abc123def456ghi789\" />");
}
@Test
public void handleTokenRendersTagsDifferentToken() {
CsrfToken token = new DefaultCsrfToken("csrfHeader", "csrfParameter",
"fooBarBazQux");
CsrfToken token = new DefaultCsrfToken("csrfHeader", "csrfParameter", "fooBarBazQux");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<meta name=\"_csrf_parameter\" content=\"csrfParameter\" />"
+ "<meta name=\"_csrf_header\" content=\"csrfHeader\" />"
+ "<meta name=\"_csrf\" content=\"fooBarBazQux\" />");
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<meta name=\"_csrf_parameter\" content=\"csrfParameter\" />"
+ "<meta name=\"_csrf_header\" content=\"csrfHeader\" />"
+ "<meta name=\"_csrf\" content=\"fooBarBazQux\" />");
}
}