请求的资源上不存在“Access-Control-Allow-Origin”标头,并且 JWT 令牌不以 Bearer String 开头

Aur*_*rel 5 java spring jwt spring-boot angular

我正在开发一个带有 Angular 和 Spring Boot 的基于网络的应用程序。Jwt 已生成,用户可以登录,但是当我想在登录后获取用户信息时,它在浏览器上显示此错误:

从源“http://localhost:4200”访问“http://localhost:8080/api/user/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin'标头存在于所请求的资源上。

在 IntelliJ 中它说: JWT 令牌不以 Bearer String 开头

我应该怎么办?

小智 7

在 Spring Security 中启用跨源引用共享的一种方法是:

在您的 Web 安全配置类(用 注释@EnableWebSecurity)中,您需要首先在HttpSecurity对象上启用 CORS:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
    .authorizeRequests()
    ...

}
Run Code Online (Sandbox Code Playgroud)

@Bean然后在同一个类中添加一个带注释的方法,该方法设置一些配置(例如允许的来源和响应标头)并返回CorsConfigurationSource

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration config = new CorsConfiguration();

    config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
    config.setAllowCredentials(true);
    config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);

    return source;
}
Run Code Online (Sandbox Code Playgroud)

Bearer关于“JWT Token does not begin with Bearer String”,您需要在请求标头中与 JWT 令牌(空格分隔)一起发送Authorization

Authorization: Bearer xxxxx.yyyyy.zzzzz