【问题标题】:How to set CSRF token in Postman如何在 Postman 中设置 CSRF 令牌
【发布时间】:2020-05-11 03:06:38
【问题描述】:

我正在使用 Spring Boot 2 和 Spring 5 来创建一个保存两个实体的应用程序:用户和用户配置文件。这是我的控制器类:

@RestController
@RequestMapping("userProfile")
public class UserProfileController {

    @Autowired
    private UserProfileService userProfileService;

    @PostMapping(produces = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public void createUserProfile(@RequestBody @Valid UserProfileDTO userProfileDTO, @AuthenticationPrincipal User user){
//code 
    }

    @GetMapping
    public ResponseEntity getUserProfile(@AuthenticationPrincipal User user){
        //code
    }
}

没什么特别的,我得到了经过身份验证的用户,然后设置并保存它,或者我根据经过身份验证的用户获取数据。我的安全配置是:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    };

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

}

现在我想用 Postman 进行测试。 GET 工作正常,我在 Postman 中添加表单数据并进行身份验证,我可以调试 get 方法。 POST 始终标识为 403 Forbidden。我不想禁用 CSRF 或/和 cors。如何测试我的应用程序,获取 CSRF 令牌并将其设置在 Postman 中?

【问题讨论】:

  • 发送第一个 GET 请求后,您是否在 cookie 中看到您的 CSRF Token?
  • 我在第一个登录表单中看到了 csrf 令牌
  • 您是否尝试在 X-CSRFToken 标头中发送 CSRF Token?

标签: spring-boot spring-security postman csrf spring-security-rest


【解决方案1】:

您必须从您的登录响应(或最初发送的任何地方)获取 XSRF 值,将其存储在您的环境中,并将其添加到您的 POST 标头中。

我正在使用 Spring Security,因此 XSRF 值作为 SET-COOKIE 标头返回,名为 XSRF-TOKEN,我将其保存为 csrftoken

然后在我的 POST 中包含一个名为 X-XSRF-TOKEN 的标题

您的标头值可能被命名为不同的名称,但这种通用方法应该可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2016-05-02
    • 2015-01-26
    • 2021-03-31
    • 2021-12-07
    • 2016-02-25
    • 1970-01-01
    相关资源
    最近更新 更多