Spring securiy cors,如何设置cookie?

时间:2018-10-23 18:40:47

标签: java spring reactjs spring-security

我正在使用Spring Security和REST体系结构。我需要将令牌保存到cookie,然后从cookie中检索此令牌。我使用了以下配置:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

我如何设置cookie:

    @Transactional
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) {
        String email = ((User) authentication.getPrincipal()).getUsername();
        String token = UUID.randomUUID().toString();
        userRepository.setTokenByEmail(token, email);
        response.addCookie(new Cookie("auth-token", token));
    }

以及如何从cookie中获取令牌:

Cookie cookie = WebUtils.getCookie(request, "auth-token");
String accessToken = null;
if(cookie != null){
    accessToken = cookie.getValue();
}

当我通过REACT APP登录到系统时,它没有将值保存到cookie,但是身份验证成功。 当我通过POSTMAN登录到系统时,它可以成功运行(该值已设置为cookie并已检索)。

为什么使用react应用程序时无法设置该值?

0 个答案:

没有答案