6
votes

I'm getting an error while querying my oauth/token endpoint.

I've configured cors enable for my resource / also tried to allow all resources but nothing worked.

XMLHttpRequest cannot load http://localhost:8080/oauth/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1111' is therefore not allowed access. The response had HTTP status code 401.

vendor.js:1837 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at CatchSubscriber.selector (app.js:7000)
    at CatchSubscriber.error (vendor.js:36672)
    at MapSubscriber.Subscriber._error (vendor.js:282)
    at MapSubscriber.Subscriber.error (vendor.js:256)
    at XMLHttpRequest.onError (vendor.js:25571)
    at ZoneDelegate.invokeTask (polyfills.js:15307)
    at Object.onInvokeTask (vendor.js:4893)
    at ZoneDelegate.invokeTask (polyfills.js:15306)
    at Zone.runTask (polyfills.js:15074)
defaultErrorLogger @ vendor.js:1837
ErrorHandler.handleError @ vendor.js:1897
next @ vendor.js:5531
schedulerFn @ vendor.js:4604
SafeSubscriber.__tryOrUnsub @ vendor.js:392
SafeSubscriber.next @ vendor.js:339
Subscriber._next @ vendor.js:279
Subscriber.next @ vendor.js:243
Subject.next @ vendor.js:14989
EventEmitter.emit @ vendor.js:4590
NgZone.triggerError @ vendor.js:4962
onHandleError @ vendor.js:4923
ZoneDelegate.handleError @ polyfills.js:15278
Zone.runTask @ polyfills.js:15077
ZoneTask.invoke @ polyfills.js:15369

With Postman everything works perfect.

My cors security configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
}

also tried to add http://localhost:1111 in allowed origins

Code in Postman:

require 'uri'
require 'net/http'

url = URI("http://localhost:8080/oauth/token")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["authorization"] = 'Basic Y2hhdHRpbzpzZWNyZXRzZWNyZXQ='
request["cache-control"] = 'no-cache'
request["postman-token"] = 'daf213da-e231-a074-02dc-795a149a3bb2'
request.body = "grant_type=password&username=yevhen%40gmail.com&password=qwerty"

response = http.request(request)
puts response.read_body
5

5 Answers

14
votes

After a lot of struggling i've overrided method configure(WebSecurity web) of class WebSecurityConfigurerAdapter because Authorization server configures this by itself and i just haven't found another solution. Also you need to permitAll "/oauth/token" Http.Options method. My method:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
}

After this we need to add cors filter to set Http status to OK. And we can now intecept Http.Options method.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}
10
votes

I found a way to fix the 401 error on Spring Security 5 and Spring Security OAuth 2.3.5 without turning off security for all OPTIONS requests on the token endpoint. I realized that you can add a security filter to the token endpoint via the AuthorizationServerSecurityConfigurer. I tried adding a CorsFilter and it worked. The only problem I have with this method is I couldn't leverage Spring MVC's CorsRegistry. If anyone can figure out how to use the CorsRegistry, let me know.

I've copied a sample configuration for my solution below:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableAuthorizationServer
public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
    //... other config

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        //... other config

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();

        // Maybe there's a way to use config from AuthorizationServerEndpointsConfigurer endpoints?
        source.registerCorsConfiguration("/oauth/token", config);
        CorsFilter filter = new CorsFilter(source);
        security.addTokenEndpointAuthenticationFilter(filter);
    }
}

1
votes

This worked for me

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception 
      {
        security.tokenKeyAccess("permitAll()")
        .checkTokenAccess("isAuthenticated()");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();

        // add allow-origin to the headers
        config.addAllowedHeader("access-control-allow-origin");

        source.registerCorsConfiguration("/oauth/token", config);
        CorsFilter filter = new CorsFilter(source);
        security.addTokenEndpointAuthenticationFilter(filter);

    }

}
0
votes

You could extend the AuthorizationServerSecurityConfiguration and override the void configure(HttpSecurity http) method to implement a custom cors configuration while leaving the rest untouched.

Here's an example:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration;
import org.springframework.web.cors.CorsConfiguration;

public class MyAuthorizationServerSecurityConfiguration extends AuthorizationServerSecurityConfiguration {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http.cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(request -> {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.addAllowedMethod("POST");
            configuration.addAllowedHeader("Content-Type");

            return configuration;
        }));
    }
}

And then, instead of using the default annotation @EnableAuthorizationServer which pulls in the default configuration class you can import the relevant classes on your own:

@Import({AuthorizationServerEndpointsConfiguration.class, MyAuthorizationServerSecurityConfiguration.class})

No need to alter any security configuration related to OPTIONS method and/or specific oauth paths.

0
votes

I had CORS errors using XMLHttpRequest to send POST /logout requests (Keycloak and Spring Cloud OidcClientInitiatedServerLogoutSuccessHandler), so I used HTML form instead:

 <form action="/logout" method="post">
    <button>Logout</button>
 </form>

it works without any issues and no CORS config is needed.