我有一个有两个metas的视图(我使用百里香):
<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 处理失败;嵌套异常是 org.thymeleaf.exceptions.TemplateProcessingException:异常 评估SpringEL表达式:&#34; _csrf.token&#34; (布局/默认:4)at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979) 在 org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:707)at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843) 在 org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:790)at org.springframework.mock.web.MockFilterChain $ ServletFilterProxy.doFilter(MockFilterChain.java:167) 在 org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) 在 org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144) 在 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) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:601)at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50) 在 org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 在 org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 在 org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 在 org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 在 org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) 在 org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) 在 org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:70) 在org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) 在 org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) 在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290)at at org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)at at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)at at org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)at at org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)at at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 在 org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 在 org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) 在org.junit.runners.ParentRunner.run(ParentRunner.java:363)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) 在 org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 在 org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 引起:org.thymeleaf.exceptions.TemplateProcessingException: 评估SpringEL表达式的异常:&#34; _csrf.token&#34; (布局/默认:4)at org.thymeleaf.spring4.expression.SpelVariableExpressionEvaluator.evaluate(SpelVariableExpressionEvaluator.java:161) 在 org.thymeleaf.standard.expression.VariableExpression.executeVariable(VariableExpression.java:154) 在 org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:59) 在 org.thymeleaf.standard.expression.Expression.execute(Expression.java:103) 在 org.thymeleaf.standard.expression.Expression.execute(Expression.java:133) 在 org.thymeleaf.standard.expression.Expression.execute(Expression.java:120) 在 org.thymeleaf.standard.processor.attr.AbstractStandardSingleAttributeModifierAttrProcessor.getTargetAttributeValue(AbstractStandardSingleAttributeModifierAttrProcessor.java:67) 在 org.thymeleaf.processor.attr.AbstractSingleAttributeModifierAttrProcessor.getModifiedAttributeValues(AbstractSingleAttributeModifierAttrProcessor.java:59) 在 org.thymeleaf.processor.attr.AbstractAttributeModifierAttrProcessor.processAttribute(AbstractAttributeModifierAttrProcessor.java:62) 在 org.thymeleaf.processor.attr.AbstractAttrProcessor.doProcess(AbstractAttrProcessor.java:87) 在 org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212) 在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) 在 org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668) 在org.thymeleaf.dom.Node.processNode(Node.java:990)at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695) 在 org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668) 在org.thymeleaf.dom.Node.processNode(Node.java:990)at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695) 在 org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668) 在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) 在 org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) 在 org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244) 在 org.springframework.test.web.servlet.TestDispatcherServlet.render(TestDispatcherServlet.java:105) 在 org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027) 在 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971) 在 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) 在 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) ... 40更多引起: org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0):属性或字段&#39;令牌&#39;无法在null处找到 org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:220) 在 org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94) 在 org.springframework.expression.spel.ast.PropertyOrFieldReference.access $ 000(PropertyOrFieldReference.java:46) 在 org.springframework.expression.spel.ast.PropertyOrFieldReference $ AccessorLValue.getValue(PropertyOrFieldReference.java:374) 在 org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88) 在 org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120) 在 org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:267) 在 org.thymeleaf.spring4.expression.SpelVariableExpressionEvaluator.evaluate(SpelVariableExpressionEvaluator.java:139) ......还有73个
我找到了一个时间解决方案,但这不是一个好的解决方案......:
<th:block th:if="${_csrf}">
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
</th:block>
答案 0 :(得分:12)
要访问您需要的会话属性
th:text="${session._csrf.headerName}">
th:text="${session._csrf.token}">
如果在测试中使用MockMvc,可以使用
设置csrf标记mvc
.perform(post("/").with(csrf()))
请参阅web security
答案 1 :(得分:2)
激活CSRF选项后,Spring Security会创建一个 _csrf 对象,其中包含令牌, headerName 和参数作为属性。您可以在两个地方使用百里香的CSRF保护:
在标题部分使用 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 请求处理器的问题是它只创建一个字符串参数,没有属性,这与上面提到的百万富翁代码不兼容:
...
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 :
中使用此课程mockMvc.perform(
get("/security/winsso")
.with(CsrfRequestPostProcessor.csrf())
.param("xxx", XXX)
.param("yyy", YYY))
.andExpect(status().isOk());
如果您正在使用百万富翁中的标题选项,请注意 asHeader 。
答案 2 :(得分:0)
你可以
@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代码:
<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>