Search code examples
spring-bootnginxspring-securitygoogle-oauthnginx-reverse-proxy

Spring security with nginx google oauth2 not working on Nginx


I created a google oauth2 login application. This works perfectly on my local machine. The front-end is react and backend is java. Here is the config file

spring:
      security:
        oauth2:
          client:
            registration:
              google:
                client-id:asdfdsaf
                client-secret: asdfsadf
                redirect-uri: http://localhost:8080/controller/oauth2/callback/google
                scope:
                - email
                - profile

Here is the java code

  `httpSecurity.cors().and().csrf().disable().authorizeRequests().antMatchers("**/api/**")
  .authenticated().and().oauth2Login().authorizationEndpoint().baseUri("/oauth2/authorize")
  .authorizationRequestRepository(cookieAuthorizationRequestRepository()).and()
  .userInfoEndpoint().oidcUserService(oidcUserService).and().redirectionEndpoint()
  .baseUri("/oauth2/callback/*").and().userInfoEndpoint().userService(customOAuth2UserService)
  .and().successHandler(oAuth2AuthenticationSuccessHandler)
  .failureHandler(oAuth2AuthenticationFailureHandler);`

Here is the error

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Jul 15 02:06:05 UTC 2020
There was an unexpected error (type=Not Found, status=404).
No message available

Here is my nginx config

# configure load-balancing
upstream backend {
  server localhost:8080;
  server localhost:8081;
  keepalive 64;
}

server {
  listen       80 default_server;
  listen       [::]:80 default_server;
  server_name  domain.app www.domain.app xxx.xx.xxx.xxx;

  location / {
  try_files $uri /index.html;
  root /var/www/build;
  index index.html index.htm;

  }


  location /controller {
    proxy_pass http://backend;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Port $server_port;
    proxy_set_header Host $http_host;
  }
}

Solution

  • Because of the way nginx works. Redirections won't work like it works on local. I tried a lot of solutions. Finally I used react-google-login to achieve the task.