spring-guides / tut-rest

Building REST services with Spring :: Learn how to easily build RESTful services with Spring

Home Page:https://spring.io/guides/tutorials/rest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

OPTIONS request from Angular returns HTTP 401 Unauthorized status

mixailom opened this issue · comments

When I invoke POST request to http://localhost:8080/oauth/token, Angular frontend application is sending preflight OPTIONS request to http://localhost:8080/oauth/token and Authorization header is not sent and I get HTTP 401 Unauthorized status.

I have found many similar issues, but all solutions are referring to use of WebSecurityConfigurerAdapter, but your sample application is using AuthorizationServerConfigurerAdapter and GlobalAuthenticationConfigurerAdapter.

Could you add solution to your sample app so OPTIONS request is not required to send Authorization header to /oauth/token, in order to be compatible to Angular applications?

I have found the solution, just add new class file:

`
package bookmarks;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@configuration
@order(-2147483645)
public class CorsConfiguration extends WebSecurityConfigurerAdapter {
@OverRide
protected void configure(HttpSecurity http) throws Exception {

    http.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/token", "/locations/**")
        .and()
            .csrf().disable()
        .authorizeRequests().anyRequest().permitAll()
        .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

}
`