Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error and 403 response with JWT token

I am trying to secure my Web Application via JWT token, but when I try to make a request from my Angular app (localhost:4200) to my Spring Boot app (localhost: 8080) I get the following error:

enter image description here

From the message alone I can see that it is a CORS issue, the problem is that I've already enabled requests from different origin at my back-end, and here is the code for it:

UPDATE: I've added OPTIONS into allowedMethods(), but the error remains the same.

@Configuration
public class AppConfiguration {

@Autowired
private Environment env;

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:4200")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD","OPTIONS")
                    .allowedHeaders("Content-Type", "Date", "Total-Count", "loginInfo")
                    .exposedHeaders("Content-Type", "Date", "Total-Count", "loginInfo")
                    .maxAge(3600);
        }
    };
}

Here is the code from my Angular app as well :

    baseUrl = 'http://localhost:8080/api/';

    constructor(private http: Http) { }


    private postaviHeadere() : RequestOptions{
        let headers = new Headers();

        console.log("***************** Set Headers *****************");
        console.log('Getting token from local storage:');
        console.log(localStorage.getItem('jwt_token'))
        console.log("***********************************************");

        headers.append('JWT_TOKEN', localStorage.getItem('JWT_TOKEN'));
        let options = new RequestOptions({headers : headers});
        console.log(options);
        return options;
    }

    getUserByToken(): any {
        return this.http.get(this.baseUrl + 'user/secured', this.postaviHeadere())
    }
like image 775
Stefan Radonjic Avatar asked Sep 15 '25 14:09

Stefan Radonjic


1 Answers

Create a java class "CorsFilterConfig" :

@Component
public class CorsFilterConfig extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
    response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
    if ("OPTIONS".equals(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        filterChain.doFilter(request, response);
    }
  }
  }

Then call it to your WebSecurityConfig :

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity

            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()

            // Un-secure H2 Database
            .antMatchers("/h2-console/**/**").permitAll()
            //whitelist swagger configuration
            .antMatchers(
                    "/swagger-resources/**",
                    "/api/swagger-resources/**",
                    "/api/**",
                    "/null/**",
                    "/v2/api-docs/**",
                    "/webjars/springfox-swagger-ui/**",
                    "/"
            ).permitAll()

            .anyRequest().authenticated();
    httpSecurity.cors();

    // Custom JWT based security filter
    JwtAuthorizationTokenFilter authenticationTokenFilter =
            new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
    httpSecurity.addFilterBefore(new CorsFilterConfig(), ChannelProcessingFilter.class);
    httpSecurity
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

}
like image 98
Denny Danu Avatar answered Sep 17 '25 03:09

Denny Danu