【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource and JWT Token does not begin with Bearer String请求的资源上不存在“Access-Control-Allow-Origin”标头,并且 JWT 令牌不以 Bearer String 开头
【发布时间】:2021-09-23 06:53:34
【问题描述】:

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

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

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

我该怎么办?

【问题讨论】:

  • 您是否启用了 CORS?如果没有,请执行此操作并将 URL 添加到源。这是如何在 Spring Boot spring.io/guides/gs/rest-service-cors 中执行此操作的指南。你检查你的 JWT 是否正确?请检查您的实施如何配置您的 JWT。

标签: java angular spring spring-boot jwt


【解决方案1】:

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

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

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

}

然后在同一个类中添加一个@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;
}

关于“JWT Token 不以 Bearer String 开头”,您需要在请求 Authorization 标头中将 Bearer 连同 JWT 令牌(空格分隔)一起发送:

Authorization: Bearer xxxxx.yyyyy.zzzzz

【讨论】:

  • CorsConfigurationSource 方法帮助我修复了错误。谢谢
【解决方案2】:

您需要检查 api 是否已在本地启动并运行。

http://localhost:8080/api/user/

您还需要检查此 api 是否启用了此 cross origin

有一个 chrome 扩展名为 Allow cors。将此扩展添加到您的浏览器,它将允许您本地的 cors。

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2013-11-29
    • 2014-07-28
    • 2014-01-19
    • 2013-12-07
    相关资源
    最近更新 更多