12
votes

I have a view with two metas (I'm using thymeleaf):

    <meta name="_csrf" th:content="${_csrf.token}" />
    <meta name="_csrf_header" th:content="${_csrf.headerName}" />

In my test controller I do this:

HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
CsrfToken csrfToken2 = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());

CustomUser user = new CustomUser();
user.setName("foo");
user.setSurname("fooo");
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new SimpleGrantedAuthority("role"));

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("foo", "fooo", grantedAuthorities);
token.setDetails(user);     

MockHttpSession session = new MockHttpSession();
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, new MockSecurityContext(token));
session.setAttribute("_csrf", csrfToken2);


this.mockMvc.perform(post("/foo/update")
            .param("param", "asdfasd")
            ....
            .session(session)
            )
        .andExpect(view().name(("foo/detail"))).andExpect(model().hasErrors())  

When I run the test I get this error (the token not found or is null):

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "_csrf.token" (layout/default:4) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843) at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144) at es.xunta.amtega.axipro.web.controller.SolicitudeControllerSaveTest.testSaveValidator(SolicitudeControllerSaveTest.java:144) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:70) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "_csrf.token" (layout/default:4) at org.thymeleaf.spring4.expression.SpelVariableExpressionEvaluator.evaluate(SpelVariableExpressionEvaluator.java:161) at org.thymeleaf.standard.expression.VariableExpression.executeVariable(VariableExpression.java:154) at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:59) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:103) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:133) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:120) at org.thymeleaf.standard.processor.attr.AbstractStandardSingleAttributeModifierAttrProcessor.getTargetAttributeValue(AbstractStandardSingleAttributeModifierAttrProcessor.java:67) at org.thymeleaf.processor.attr.AbstractSingleAttributeModifierAttrProcessor.getModifiedAttributeValues(AbstractSingleAttributeModifierAttrProcessor.java:59) at org.thymeleaf.processor.attr.AbstractAttributeModifierAttrProcessor.processAttribute(AbstractAttributeModifierAttrProcessor.java:62) at org.thymeleaf.processor.attr.AbstractAttrProcessor.doProcess(AbstractAttrProcessor.java:87) at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212) at org.thymeleaf.dom.Node.applyNextProcessor(Node.java:1017) at org.thymeleaf.dom.Node.processNode(Node.java:972) at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695) at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668) at org.thymeleaf.dom.Node.processNode(Node.java:990) at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695) at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668) at org.thymeleaf.dom.Node.processNode(Node.java:990) at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695) at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668) at org.thymeleaf.dom.Node.processNode(Node.java:990) at org.thymeleaf.dom.Document.process(Document.java:93) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1155) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335) at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244) at org.springframework.test.web.servlet.TestDispatcherServlet.render(TestDispatcherServlet.java:105) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) ... 40 more Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'token' cannot be found on null at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:220) at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94) at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:46) at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:374) at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88) at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120) at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:267) at org.thymeleaf.spring4.expression.SpelVariableExpressionEvaluator.evaluate(SpelVariableExpressionEvaluator.java:139) ... 73 more

I found a temporal solution but it not is a good solution..:

<th:block th:if="${_csrf}">
   <meta name="_csrf" th:content="${_csrf.token}" />
   <meta name="_csrf_header" th:content="${_csrf.headerName}" />
</th:block> 
3

3 Answers

18
votes

To access a session attribute you would need

th:text="${session._csrf.headerName}">
th:text="${session._csrf.token}">

see spring thymeleaf

If you use MockMvc in your tests you can set the csrf token with

mvc
.perform(post("/").with(csrf()))

see web security

4
votes

When the CSRF option is activated, Spring Security creates a _csrf object having token, headerName and parameter as properties. There are two places where you can use the CSRF protection in thymeleaf:

  • Using meta tags in the header section.

    <meta name="_csrf" th:content="${_csrf.token}" />
    <meta name="_csrf_header" th:content="${_csrf.headerName}" />
    
  • Using hidden fields in the forms.

    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
    

The issue with the SecurityMockMvcRequestPostProcessors.csrf request processor is that it only creates one string parameter, with no properties, which is not compatible with the thymeleaf code mentioned above:

    ...
    request.addHeader(token.getHeaderName(), tokenValue);
    ...
    request.setParameter(token.getParameterName(), tokenValue);

My workaround was to make a custom RequestPostProcessor adding the token as a request attribute instead of a request parameter:

    package ...;

    import org.springframework.mock.web.MockHttpServletRequest;
    import org.springframework.mock.web.MockHttpServletResponse;
    import org.springframework.security.test.web.support.WebTestUtils;
    import org.springframework.security.web.csrf.CsrfToken;
    import org.springframework.security.web.csrf.CsrfTokenRepository;
    import org.springframework.test.web.servlet.request.RequestPostProcessor;

    /**
     * A request post processor to add <em>csrf</em> information.
     */
    public class CsrfRequestPostProcessor implements RequestPostProcessor {

        private boolean useInvalidToken = false;

        private boolean asHeader = false;


        @Override
        public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
            CsrfTokenRepository repository = WebTestUtils.getCsrfTokenRepository(request);
            CsrfToken token = repository.generateToken(request);
            repository.saveToken(token, request, new MockHttpServletResponse());
            String tokenValue = useInvalidToken ? "invalid" + token.getToken() : token
                    .getToken();
            if (asHeader) {
                request.setAttribute(token.getHeaderName(), token);
            }
            else {
                request.setAttribute(token.getParameterName(), token);
            }
            return request;
        }

        public RequestPostProcessor invalidToken() {
            this.useInvalidToken = true;
            return this;
        }

        public RequestPostProcessor asHeader() {
            this.asHeader = true;
            return this;
        }

        public static CsrfRequestPostProcessor csrf() {
            return new CsrfRequestPostProcessor();
        }
    }

You can use this class directly in the MockMvc:

mockMvc.perform(
        get("/security/winsso")
                .with(CsrfRequestPostProcessor.csrf())
                .param("xxx", XXX)
                .param("yyy", YYY))
        .andExpect(status().isOk());

Pay attention at the asHeader if you're using the header option in thymeleaf.

1
votes

You can

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests {

  @Autowired
  private WebApplicationContext context;

  @Autowired
  private Filter springSecurityFilterChain;

  private MockMvc mvc;

  @Before
  public void setup() {
      mvc = MockMvcBuilders
              .webAppContextSetup(context)
              .addFilters(springSecurityFilterChain)
              .build();
  }
@Test
public void verifiesHomePageLoads() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/index"))
            .andExpect(MockMvcResultMatchers.model().hasNoErrors())
            .andExpect(MockMvcResultMatchers.model().attributeExists("word"))
            .andExpect(MockMvcResultMatchers.model().attributeExists("w"))
            .andExpect(MockMvcResultMatchers.model().attributeExists("mobil"))
            .andExpect(MockMvcResultMatchers.view().name("/index"))
            .andExpect(MockMvcResultMatchers.status().isOk());

}

}

thymleaf code:

 <form id="suggetWord" name="suggetWord" data-th-action="@{/suggest-word(${_csrf.parameterName}=${_csrf.token})}" ></form>
 <form class="mainForm" th:id="word-search" th:name="word-search" data-th-action="@{/word-search(${_csrf.parameterName}=${_csrf.token})}"  > </form>