Spring Boot JWT CORS with Angular 6

后端 未结 5 950
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 22:24

I am using JWT in my Spring Boot app. When I try to login from the Angular 6 client, I get the CORS error

Access to XMLHttpRequest at \'http://localhost:8082         


        
5条回答
  •  春和景丽
    2021-01-02 22:43

    I was also facing the same issue.When i tried from postman it worked fine but same call made from react app i faced issue.

    Generally we disable cors in configuration while working with the spring security. But here you should allow it. Check the below code snippet.

    Just added http.cors(); in below code

    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserDetailsService userDetailsService;
        
        @Autowired
        private JwtFilter jwtFilter;
    
            
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
                }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            
     http.csrf().disable().authorizeRequests().antMatchers("/secure/authenticate")
            .permitAll().anyRequest().authenticated()
            .and().exceptionHandling().and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);;
            http.cors();
                    
        }
    
        @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
        
        @Bean
        public PasswordEncoder getPasswordEncoder() {
            return NoOpPasswordEncoder.getInstance();
        }
        
        
    }
    

提交回复
热议问题