使用 mockmvc 和 junit 添加 csrf 令牌
Add csrf token with mockmvc and junit
我有两个元视图(我正在使用 thymeleaf):
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
在我的测试控制器中,我这样做:
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())
当我 运行 测试时出现此错误(令牌未找到或为空):
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.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.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access[=13=]0(ParentRunner.java:58) at
org.junit.runners.ParentRunner.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[=13=]0(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
我找到了一个暂时的解决方案,但它不是一个好的解决方案..:[=14=]
<th:block th:if="${_csrf}">
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
</th:block>
要访问您需要的会话属性
th:text="${session._csrf.headerName}">
th:text="${session._csrf.token}">
如果您在测试中使用 MockMvc,您可以使用
设置 csrf 令牌
mvc
.perform(post("/").with(csrf()))
当 CSRF 选项被激活时,Spring 安全创建一个 _csrf object 具有 token,header名称 和 参数 作为属性。在 thymeleaf 中有两个地方可以使用 CSRF 保护:
在 header 部分使用 meta 标签。
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
在表单中使用隐藏 字段。
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
SecurityMockMvcRequestPostProcessors.csrf 请求处理器的问题是它只创建一个字符串参数,没有属性,这与上面提到的 thymeleaf 代码不兼容:
...
request.addHeader(token.getHeaderName(), tokenValue);
...
request.setParameter(token.getParameterName(), tokenValue);
我的解决方法是制作自定义 RequestPostProcessor 添加令牌作为请求属性而不是请求参数:
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();
}
}
你可以直接在MockMvc中使用这个class:
mockMvc.perform(
get("/security/winsso")
.with(CsrfRequestPostProcessor.csrf())
.param("xxx", XXX)
.param("yyy", YYY))
.andExpect(status().isOk());
如果您在 thymeleaf 中使用 header 选项,请注意 asHeader。
你可以
@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());
}
}
百里香叶代码:
<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>
我有两个元视图(我正在使用 thymeleaf):
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
在我的测试控制器中,我这样做:
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())
当我 运行 测试时出现此错误(令牌未找到或为空):
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.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.run(ParentRunner.java:290) at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access[=13=]0(ParentRunner.java:58) at org.junit.runners.ParentRunner.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[=13=]0(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
我找到了一个暂时的解决方案,但它不是一个好的解决方案..:[=14=]
<th:block th:if="${_csrf}">
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
</th:block>
要访问您需要的会话属性
th:text="${session._csrf.headerName}">
th:text="${session._csrf.token}">
如果您在测试中使用 MockMvc,您可以使用
设置 csrf 令牌mvc
.perform(post("/").with(csrf()))
当 CSRF 选项被激活时,Spring 安全创建一个 _csrf object 具有 token,header名称 和 参数 作为属性。在 thymeleaf 中有两个地方可以使用 CSRF 保护:
在 header 部分使用 meta 标签。
<meta name="_csrf" th:content="${_csrf.token}" /> <meta name="_csrf_header" th:content="${_csrf.headerName}" />
在表单中使用隐藏 字段。
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
SecurityMockMvcRequestPostProcessors.csrf 请求处理器的问题是它只创建一个字符串参数,没有属性,这与上面提到的 thymeleaf 代码不兼容:
...
request.addHeader(token.getHeaderName(), tokenValue);
...
request.setParameter(token.getParameterName(), tokenValue);
我的解决方法是制作自定义 RequestPostProcessor 添加令牌作为请求属性而不是请求参数:
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();
}
}
你可以直接在MockMvc中使用这个class:
mockMvc.perform(
get("/security/winsso")
.with(CsrfRequestPostProcessor.csrf())
.param("xxx", XXX)
.param("yyy", YYY))
.andExpect(status().isOk());
如果您在 thymeleaf 中使用 header 选项,请注意 asHeader。
你可以
@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());
}
}
百里香叶代码:
<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>