Spring Boot JWT Cors 不适用于 Angular 8

Posted

技术标签:

【中文标题】Spring Boot JWT Cors 不适用于 Angular 8【英文标题】:Spring Boot JWT Cors Not Working with Angular 8 【发布时间】:2020-11-19 07:21:28 【问题描述】:

我在 Spring Boot 中有后端服务,在 Angular 8 中有 UI。 我启用了 JWT,因此所有 api 调用都需要通过传递 Authorizarion 标头以 JWT 令牌作为值

来完成

我像下面这样设置 CORS:

@SpringBootApplication
public class MyServicesApplication 

    public static void main(String[] args) 
        SpringApplication.run(MyServicesApplication.class, args);
    
    
    @Bean
    public WebMvcConfigurer corsConfigurer() 
        return new WebMvcConfigurer() 
            @Override
            public void addCorsMappings(CorsRegistry registry) 
                registry.addMapping("/**").allowedOrigins("http://localhost:4200");
            
        ;
        
    

在此之后,我可以访问登录 API,即

http://localhost:8080/login

但我无法访问任何受保护的路线。调用后端 API 服务时出现以下错误。

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/data' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我已经为我的 JWT 设置了这样的 WebSecurity。这对案件有影响吗?

@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter 
    @Autowired
    private UserDetailsService myUserDetailsService;
    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
        auth.userDetailsService(myUserDetailsService);
    

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

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean();
    

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception 
        httpSecurity.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().anyRequest()
                .authenticated().and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    

【问题讨论】:

【参考方案1】:

在你的WebSecurityConfig#configure(HttpSecurity httpSecurity)

更新如下

httpSecurity
    .cors()
    ...

【讨论】:

【参考方案2】:

添加您的 WebSecurityConfig 类:

@Bean
CorsConfigurationSource corsConfigurationSource() 
    CorsConfiguration configuration = new CorsConfiguration();

    //here you add all origins possible
    configuration.setAllowedOrigins(Arrays.asList("http://localhost", "http://localhost:8080", "http://localhost:4200"));

    configuration.setAllowedMethods(Arrays.asList("GET", "PUT", "POST","OPTIONS", "DELETE"));
    configuration.setAllowedHeaders(Arrays.asList("authorization","content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;

您可以在每个@RestController 类中添加注释@CrossOrigin,在这种情况下,我以最通用的方式编写:

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestControler
public class YourController 

...


【讨论】:

你只是在创建一个bean,你在哪里使用它?

以上是关于Spring Boot JWT Cors 不适用于 Angular 8的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot CORS 过滤器不适用于 AngularJS

Spring Boot - CORS 过滤器适用于 GET,但不适用于其他 HTTP 动词

Spring Security 保护路由 hasRole,hasAuthority 不适用于 CORS http 请求

Spring boot、jwt、jersey、spring security和CORS问题

Angular集成Spring Boot,Spring Security,JWT和CORS

@CrossOrigin 不适用于 spring-boot-starter-web 2.5.2