Skip to Content
Menu
This question has been flagged
3 Replies
1863 Views

Hi,


I'd greatly appreciate any help with the following.


Problem

I'm trying to enable "login with Google" on my website but I keep getting the above error. 


Setup

  • Odoo version: v18 Community Edition
  • Server: Cloud server
  • Web Protocol: HTTPS, using NGINX as a reverse proxy
  • web.base.url: https://my-domain.com
  • web.base.url.freeze: True

Nginx Configuration

server {
    server_name my-domain.com www.my-domain.com subdomain.my-domain.com;

    proxy_buffers 16 64k;
    proxy_buffer_size 128k;

    # Proxy requests to Odoo
    location / {
        proxy_pass http://127.0.0.1:8069;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
​}

# Gzip configuration
    gzip_types text/css text/less text/plain text/xml application/xml application/json application/javascript;
    gzip on;

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-domain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

​server {
    if ($host = subdomain.my-domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = www.my-domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = my-domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    server_name my-domain.com www.my-domain.com subdomain.my-domain.com;
    return 404; # managed by Certbot
}


Odoo Config File

[options]
admin_passwd = ********
db_host = False
db_port = False
db_user = odoo
db_password = False
addons_path = /opt/odoo/odoo/addons,/opt/odoo/custom-addons
logfile = /var/log/odoo/odoo.log
proxy_mode = True


Oauth2 Error

Error 400: redirect_uri_mismatch

You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.

If you're the app developer, register the redirect URI in the Google Cloud Console.

Request details: redirect_uri=http://www.my-domain/auth_oauth/signin flowName=GeneralOAuthFlow


Observations

It appears that, despite https working correctly on the site, NGINX is still passing http to Google.


Temporary Workaround

If I add the http version of my domain to my Google cloud project, it works correctly and allows test users to sign up and log in, but the drawback is that you can't publish the app with http URIs and I need external users to have this functionality.


Other Things I've Tried

I saw on one of the thousands of posts I've googled that what's being passed to Google is a Werkzeug variable that's picked up automatically from the sitemap. I don't know how accurate this information is but I acted on it and manually edited the sitemap, replacing http with https. This made no difference.


Conclusion

I have no idea why ths isn't working as expected and I don't understand why it's so difficult.

I'm already bald but if I had any hair, I would have pulled it all out by now!

Please help 🙏🏾

Avatar
Discard
Best Answer

Hi everyone!

In my case, with Odoo 18 with Nginx and despite having the web.base.url set to HTTPS, the Google OAuth authentication wasn't working. After analyzing and updating the code to make it more flexible, I've created a fixed version of the auth_oauth module that solves the common issues.


🔧 Issues Resolved:

🔒 HTTP URLs being sent to Google OAuth2

👤 Authentication failure with existing users

🌐 Google's redirect_uri_mismatch error

✉️ Duplicate email handling


💻 Code Improvements and changes made:

In controllers/main.py - list_providers method:


Added logic to force HTTPS on redirect URL Prevents Google rejection for HTTP use Maintains compatibility with existing configurations


  • Changes made in file main.py


  def list_providers(self):

      try:

          providers = request.env['auth.oauth.provider'].sudo().search_read([('enabled', '=', True)])

      except Exception:

          providers = []

      for provider in providers:

          # Force HTTPS in redirect URL

          base_url = request.httprequest.url_root

          if base_url.startswith('http://'):

              base_url = base_url.replace('http://', 'https://', 1)

          return_url = base_url + 'auth_oauth/signin'

          state = self.get_state(provider)

          params = dict(

              response_type='token',

              client_id=provider['client_id'],

              redirect_uri=return_url,

              scope=provider['scope'],

              state=json.dumps(state),

              # nonce=base64.urlsafe_b64encode(os.urandom(16)),

          )

          provider['auth_link'] = "%s?%s" % (provider['auth_endpoint'], werkzeug.urls.url_encode(params))

      return providers


  • Changes made in /models/res_users.py

 _auth_oauth_validate method:

Added detailed logging of the validation process Better error handling and response validation Clearer information about the authentication process


 _auth_oauth_signin method:

User search by email was implemented in addition to oauth_uid Automatic management of existing users Updating OAuth credentials for existing users Improved logging for diagnostics


@api.model

  def _auth_oauth_validate(self, provider, access_token):

          """ return the validation data corresponding to the access token """

          oauth_provider = self.env['auth.oauth.provider'].browse(provider)

          validation = self._auth_oauth_rpc(oauth_provider.validation_endpoint, access_token)

          if validation.get("error"):

              _logger.error("OAuth validation error: %s", validation['error'])

              raise Exception(validation['error'])

          if oauth_provider.data_endpoint:

              data = self._auth_oauth_rpc(oauth_provider.data_endpoint, access_token)

              validation.update(data)

          # Logging the validation data

          subject = next(filter(None, [

              validation.pop(key, None)

              for key in [

                  'sub',  # standard

                  'id',  # google v1 userinfo, facebook opengraph

                  'user_id',  # google tokeninfo, odoo (tokeninfo)

              ]

          ]), None)

          if not subject:

              _logger.error("Missing subject identity in validation data")

              raise AccessDenied('Missing subject identity')

          validation['user_id'] = subject

          return validation


  @api.model

  def _auth_oauth_signin(self, provider, validation, params):

          """ retrieve and sign in the user corresponding to provider and validated access token

              :param provider: oauth provider id (int)

              :param validation: result of validation of access token (dict)

              :param params: oauth parameters (dict)

              :return: user login (str)

              :raise: AccessDenied if signin failed

              This method can be overridden to add alternative signin methods.

          """

          oauth_uid = validation['user_id']

          email = validation.get('email')

          try:

              # First search for oauth_uid

              oauth_user = self.search([("oauth_uid", "=", oauth_uid), ('oauth_provider_id', '=', provider)])

              if not oauth_user and email:

                  # If not found, search by email.

                  oauth_user = self.search([("login", "=", email)])

                  if oauth_user:

                      # If the user with that email exists, we update their OAuth data

                      oauth_user.write({

                          'oauth_provider_id': provider,

                          'oauth_uid': oauth_uid,

                          'oauth_access_token': params['access_token']

                      })

              if not oauth_user:

                  raise AccessDenied()

              assert len(oauth_user) == 1

              oauth_user.write({'oauth_access_token': params['access_token']})

              return oauth_user.login

          except AccessDenied as access_denied_exception:

              if self.env.context.get('no_user_creation'):

                  return None

              state = json.loads(params['state'])

              token = state.get('t')

              values = self._generate_signup_values(provider, validation, params)

              try:

                  login, _ = self.signup(values, token)

                  return login

              except (SignupError, UserError) as e:

                  _logger.error("Failed to create new user: %s", str(e))

                  raise access_denied_exception

You can find it on github:

(Sorry but I can't post links yet.)


diegonaranjo/odoo-addons-auth_oauth


Please make sure to backup your existing module before making any changes. If you encounter any issues or need help, feel free to open an issue on the GitHub repository.

Hope this helps!

Avatar
Discard
Author Best Answer

I've found a solution.

he issue stems from a bug in Odoo's code. The code uses an HTTP request to get your website's URL, but this function relies on a Werkzeug variable, and it completely ignores the web.base.url parameter that you've set in Odoo's settings. If you're running Odoo behind a proxy(like NGINX), the resulting URL will always be wrong.


I corrected this error by rewriting the code to use the web.base.url parameter as a means of retrieving the site's URL, thus bypassing Werkzeug completely. Here's an example of the code I used:


request.env['ir.config_parameter'].sudo().get_param('web.base.url')


Please note that the function MUST be run as sudo. If not, you'll get "403 - access denied" errors".


My advice to you is to be this:


search the Odoo repository on GitHub for references to "base_URL".


Where they appear in files relating to Google authentication, edit the corresponding file on your server by replacing those lines with the code example above.


Good luck!


Avatar
Discard
Best Answer

I am facing this error. Tried all solution on the forums. Please help.

Avatar
Discard
Related Posts Replies Views Activity
0
May 25
265
3
Mar 25
833
2
Feb 25
2870
1
Feb 25
862
1
May 25
568