How to Fix CORS Error in Spring boot JWT Security

Solution for CORS error in Sprint Boot Security deployed in Heroku

CORS error is one of the most annoying errors which one can encounter while developing web applications.

CORS is a mechanism that allows Server to indicate to Browser to allow connections from origins other than its own. Browser will send a pre-flight connection request(an Options request) to server to check if server will allow the request. If server allows the request from this origin it will respond with Access-Control-Allow-Origin.

I encountered this error while developing an Angular application. The back-end of this application was developed in Java spring and deployed to Heroku.

Once I deployed the front-end angular application, I ended with the CORS error. After googling a fair bit of time , I found most solutions out there were for a simple Spring boot application but none for my particular use case.

My application had JWT based Spring Security, so nothing seemed to work.

But after lots of googling below is the solution I found

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS,"*").permitAll()//allow CORS option calls
    .antMatchers("/oauth/token").permitAll()
    .anyRequest().authenticated()
    .and()
    .formLogin()
    .and()
    .httpBasic();
}

Here .csrf().disable is needed, but adding this alone won’t solve the problem.

Options requests are sent before-hand as pre-flight requests, but since server does not respond with Access-Control-Allow-Origin due to Spring Security, we get CORS error for all subsequent calls.

So add .antMatchers(HttpMethod.OPTIONS,"*").permitAll() to resolve this issue. This allows all Options requests to be permissible.

For more articles related to Java and Spring boot check out here.