RestTemplate表单/数据授权请求:无法使用XSRF-TOKEN获取Cookie

时间:2019-09-04 09:12:27

标签: java authentication spring-security resttemplate x-xsrf-token

授权后,我需要获得XSRF令牌。我使用下一个代码:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
    map.add("username", "valera");
    map.add("password", "111111");

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

    ResponseEntity<String> response = new RestTemplateBuilder().build().postForEntity( "http://localhost:50101/login",
    request ,
    String.class );

我得到一个OK状态的响应,以及Set-Cookie标头中带有会话的标头。但是我没有得到XSRF-TOKEN。 当我与Postman进行相同的Post请求时,我会得到令牌。通过Postman,我可以获得与restTemplate相同的标题,并且还可以通过会话和XSRF-TOKEN获得cookie。

enter image description here

enter image description here

在授权服务器上,我使用org.springframework.boot:spring-boot-starter-security。安全配置是下一个:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.cors()
            .and()
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
            .and()
            .authorizeRequests()
            .regexMatchers("/health")
            .permitAll()
            .anyRequest().authenticated()
            .and()
            .logout()
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
            .invalidateHttpSession(true)
            .clearAuthentication(true)
            .and()
            .formLogin()
            .permitAll()
            .successHandler(new HttpStatusAuthenticationSuccessHandler())
            .failureHandler(new SimpleUrlAuthenticationFailureHandler());
}

为什么我的restTemplate无法在请求中获得XSRF-TOKEN?还是如何配置将XSRF-TOKEN添加到响应头的安全性?

0 个答案:

没有答案