Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Google Oauth issue of https redirect_uri mismatch

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
odoo8oauth2
5 Respuestas
11876 Vistas
Avatar
Steve turri

When you click login with google, the redirect uri is being changed from https:// to http://

I checked my parameters to make sure the web.base.url is set to the correct https value.  
I also added a web.base.url.freeze value of True.

I can modify line 74 of addons/auth_oauth/controllers.main.py and explicitly define the url and it works.

redirect = request.params.get('redirect') or 'web'
if not redirect.startswith(('//', 'http://', 'https://')):
    redirect = '%s%s' % (request.httprequest.url_root, redirect[1:] if redirect[0] == '/' else redirect)

We are using nginx.

0
Avatar
Descartar
paidy kumar

i am also facing same issue any solution please

Avatar
Diego Naranjo
Mejor respuesta

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!

0
Avatar
Descartar
Avatar
Martin Riley
Mejor respuesta

I'm also getting this error and it's driving me crazy!

I have a temporary workaround of adding the http version of the URI to my Google cloud project, which will allow test users to sign up and log in, but the drawback is that you can't publish the app with http URIs.

0
Avatar
Descartar
Avatar
Matthieu Schmid
Mejor respuesta

Still no answer ? I have the same issue with odoo 17 community on premise

0
Avatar
Descartar
Avatar
BL
Mejor respuesta

I am also facing this same problem with Odoo 17 on-premise.

Did anyone find a solution after 8 years?

0
Avatar
Descartar
Avatar
Shen
Mejor respuesta

odoo 16, encountered the same redirect_uri_mismatch problem

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.
要求詳情: redirect_uri=http://xxx.ccc.com/auth_oauth/signin

0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Is OAuth2 supported in the Odoo 18 Community Edition?
oauth2
Avatar
Avatar
Avatar
2
sept 25
3118
Can't find where to put the client secret
oauth2
Avatar
Avatar
2
oct 23
5472
Connecting Okta with Odoo using Oauth
oauth2
Avatar
Avatar
1
jul 23
5427
Selecting items for one2many relation Resuelto
odoo8
Avatar
Avatar
Avatar
2
dic 22
15628
How to upload files automatically on attachments on button click ?
odoo8
Avatar
Avatar
1
nov 21
5708
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now