Gururaj H Gowda
Gururaj H Gowda

Reputation: 99

Spring Boot OAuth2 CORS issue with GitHub single SignOn with Angular frontend

I've a sample spring boot app running on port 8080 whose APIs are protected with OAuth2 interface which needs to be authorised by GitHub. I'm trying to call these APIs from a sample Angular 6 app running on port 4200 with the bearer token included in the request header.

For the backend I've added a custom filter with highest precedence which responds with 200 OK status code for all the HTTP Options requests so the CORS is enabled for the spring security endpoints.

When I call the APIs with the valid authorisation token from my angular app I get the below error. Please find the screenshot Response headers Request Headers

Basically the API calls are redirected to the authorisation server for validity where the Angular's origin is not whitelisted.

I managed to get through this error by running my angular app as a proxy to my backend server by using --proxy-config on my webpack dev server.

My problem is: In production my angular app is deployed on Cloud Foundry, where the app runs on ngInx, Is there a hack to run the angular app as a proxy server on ngInx. I mostly prefer to have the configuration at the application level since it would be difficult to get the root access to modify the ngInx.config file. Or is there any better way to do this? I prefer to have both the frontend and backend hosted as separate components.

Thanks in advance.

Upvotes: 2

Views: 533

Answers (2)

Gururaj H Gowda
Gururaj H Gowda

Reputation: 99

I changed my spring boot app from being an oAuth client to be a resource server i.e. changed @EnableOauth2Sso annotation with @EnableResourceServer and converted my angular app to be the oAuth client and talk to the authorization server to fetch access token and access the resources.

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32535

For the backend I've added a custom filter with highest precedence which responds with 200 OK status code for all the HTTP Options requests so the CORS is enabled for the spring security endpoints.

No, response code to options is only one part of story. All that matters is the reason why CORS happens in the first place. Most probably browsers ask is it ok to send X,Y,Z... headers or do A,B,C... requests from SOMEWYHERE and answers to those questions must be included in options response to tell browser it is ok to do what it is going to do. Using backend proxy is just plain HACK that should be used as last resort.

Check browser errors carefully as it will have details on why preflight failed (eg header not allowed, origin not allowed etc).

In your case it is access-control-allow-origin header missing in preflight response so in short - no you don't have CORS enabled int your Spring API.

Upvotes: 0

Related Questions