【问题标题】:Passing JSessionId and CSRF-Token in Spring Boot for POST在 Spring Boot 中为 POST 传递 JSessionId 和 CSRF-Token
【发布时间】:2019-05-18 07:28:18
【问题描述】:

我有 Spring Boot 2.1.0.RELEASE 应用程序。我想了解登录和 CSRF 配置,所以我首先发送一个 GET 请求:

 GET http://localhost:8080/devices
 Accept: application/json
 Authorization: Basic user test

对我收到的 JSessionID 再次执行相同操作,也可以:

GET http://localhost:8080/devices
Accept: application/json
#Authorization: Basic user test
cookie: JSESSIONID=162A7A29081CC89EA444423D9508F286

到目前为止一切都很好。我收到了 200 条回复,并获得了一个 CSRF 令牌。后一种:

HTTP/1.1 200 
Set-Cookie: XSRF-TOKEN=2adcabdd-d804-4f13-a2a6-b95621ce868c; Path=/
....

好的,现在我想直接尝试 POST 请求:

POST localhost:8080/devices/check
Content-Type: application/json
#Authorization: Basic user password
cookie: JSESSIONID=162A7A29081CC89EA444423D9508F286; XSRF-TOKEN=2adcabdd-d804-4f13-a2a6-b95621ce868c
#X-XSRF-TOKEN: 2adcabdd-d804-4f13-a2a6-b95621ce868c

但独立地,如果我尝试通过 Cookie 或 Header 传递 XSRF 令牌,我将收到 403 Forbidden。

这是我的 Spring Security 配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository
                        .withHttpOnlyFalse()).and()
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic().and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

}

我在这里做错了什么?

仅供参考:我正在使用 IntelliJ HTTP 客户端发送请求。

【问题讨论】:

  • 请调试一下,看看403是什么原因?它是无效的 CSRF 令牌还是?

标签: spring spring-boot spring-security csrf


【解决方案1】:

这是我所做的:

从您的 RequestContext 中检索您的 cookie:

function getMyToken() {
    Cookies[] cookies = getRequestContext().getRequest().getCookies()
    for (cookie in cookies) {
        if (cookie.getName().equals("XSRF-TOKEN")) return cookie.getValue()
    }
}

然后以我的形式:

<input name="_csrf" value="getMyToken()"/>

它对我有用。

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2017-04-17
    • 2019-06-25
    • 2018-02-17
    • 2020-12-29
    • 2015-10-25
    相关资源
    最近更新 更多