user9247715
user9247715

Reputation:

Failed to load http://localhost:9999/auth-service/oauth/token: Response for preflight has invalid HTTP status code 401

Trying to generate Oauth2 token I have used Spring Boot Oauth2 and Angular 5

In postman and curl I'm able to generate the token by passing the appropriate values and with the same parameter it is not working in the Angular POST

Error

OPTIONS http://localhost:9999/auth-service/oauth/token 401 () Failed to load http://localhost:9999/auth-service/oauth/token: Response for preflight has invalid HTTP status code 401.

Angular Code

login2(credentials){
    let headers = new Headers();
    var creds = 'client_id=finance-service&client_secret=finance&grant_type=client_credentials&socpe=server';

    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append("Authorization", "Basic " + btoa("finance-service:finance"));
    console.log(btoa("finance-service:finance"))
    return new Promise((resolve) =>{
        this.http.post(SMSGlobal.authPath, creds, {headers : headers})
        .subscribe((data) =>{
            console.log(data.json());
        },
        (error) =>{
            console.log(error);
        })
    })
  }

I've configured CORS in Backend as well

Upvotes: 2

Views: 1219

Answers (2)

Mike
Mike

Reputation: 11

In the AuthorizationServerConfigurerAdapter you must configure the custom TokenEndpointAuthenticationFilter

public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers", "Content-Length, Content-Type, X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "*");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }
}

AuthorizationServerConfigurerAdapter:

 @Configuration
 @EnableAuthorizationServer
 public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
                       .addTokenEndpointAuthenticationFilter(new CorsFilter());
        }
}  

Each request on the path / oauth / enters in the filter and if the request method is OPTIONS the error will be avoided: Response for preflight has invalid HTTP status code 401.

Upvotes: 1

Wenyan
Wenyan

Reputation: 273

I have the same issue in the project Spring 5 + Angular 5. I found the solution from here

The CORS configuration should be added to fix this issue. The code is as per following

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() { 

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:4200");
    config.addAllowedHeader("Authorization");
    config.addAllowedHeader("Content-Type");
    config.addAllowedHeader("Accept");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("OPTIONS");
    config.setMaxAge(3600L);
   // source.registerCorsConfiguration("/oauth/token", config); // Add "/oauth/token" explicitly
    source.registerCorsConfiguration("/**", config); // Global for all paths

    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
}

Upvotes: 1

Related Questions