[英]Invalid CSRF Token 'null' when i using PUT method with Spring Security
[英]Spring Rest Service - Invalid CSRF token when I attempt to login
我有一個Spring MVC REST服務,啟用了Spring Security(3.2.5.RELEASE)。 當我打開@EnableWebMvcSecurity時,會在http:// localhost:8080 / login為我自動生成一個登錄表單。 如果我使用此表單登錄,一切正常。
當我嘗試通過直接發送POST請求登錄時,會發生此問題。 在我的帖子請求中,我提供了用戶名和密碼。 我還包括http標頭'X-CSRF-TOKEN',對於標頭值,我使用我看到的JSESSIONID已在cookie中生成。 但是,當我發送此POST請求時,我得到以下結果:
HTTP Status 403 - Invalid CSRF Token '29F5E49EFE8D758D4903C0491D56433E'
was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
我究竟做錯了什么? 我提供了錯誤的令牌價值嗎? 這是什么JSESSIONID? 如果我沒有為此標題輸入值,或者一起省略標題,則會告訴我“找到空的CSRF標記”。
以下是我的Spring Security配置:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/secure/**").authenticated()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.and()
.httpBasic()
.and()
.csrf();
}
}
我真的很感激任何幫助! 提前致謝!
(1)在所有AJAX請求中包含CSRF令牌。
$(function () {
var token = $('#logoutform>input').val();
var header = $('#logoutform>input').attr('name');
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader('X-CSRF-TOKEN', token);
});
});
(2)簡單的要求。
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
您需要在提交登錄表單時發送csrf
令牌。 請在HTML表單中添加以下行:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
你需要<meta name="_csrf" content="${_csrf.token}"/>
https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-亮點-CSRF保護/#Ajax的請求
或者如果你使用的是thymeleaf <meta name="_csrf" th:content="${_csrf.token}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.