Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add csrf token with mockmvc and junit

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> 
like image 433
oscar Avatar asked Feb 29 '16 13:02

oscar


People also ask

What is MockMvc in JUnit?

MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container. In this MockMVC tutorial, we will use it along with Spring boot's WebMvcTest class to execute Junit testcases that tests REST controller methods written for Spring boot 2 HATEOAS example.

How do I make a MockMvc instance?

There are two ways to create a MockMvc instance: using Spring Boot's auto-configuration or hand-crafting it. Following Spring Boot's auto-configuration principle, we only need to annotate our test with @WebMvcTest .

Is MockMvc a unit test?

MockMvc is defined as a main entry point for server-side Spring MVC testing. Tests with MockMvc lie somewhere between between unit and integration tests.


1 Answers

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

like image 189
Stefan Isele - prefabware.com Avatar answered Oct 04 '22 07:10

Stefan Isele - prefabware.com