Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
Spring Oauth with multiple users tables

I am creating an application using Spring with Oauth2 as a backend for two apps (provider app and a consumer app). I have two different types of users; Providers, and consumers, each with its own db table. The problem I am facing is that I cannot find a way to know if the request is coming from a provider or a customer, as each one will be in a different db table.

The username is Not unique between the two tables. So, a provider and a consumer can have the same username (and password). I think any of the following solutions will suffice, however, I can’t find any way to implement any of them.

  • Having two different endpoints for each user class. e.g. “/provider/oauth/token” and “/consumer/oauth/token”. Each with its custom authentication manager.
  • Or: Having two authorization servers in the same Spring application, and then mapping their “/oauth/token” to different endpoints.
  • Or: Sending custom data in the oauth request to know where the request is coming from, and then dynamically selecting an authentication manager.
  • Or: Associating different authentication manager to different OAuth clients, and then ensuring that each app will have its respective client ID.

If any of these solutions is possible, or if there is another way to accomplish this, please let me know. Any help is appreciated.

Edit - Solution

Following the answer below, I added another client with a different client ID, check the id in the UserDetailsService and then decide which db to use. Here is the code:

  public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
            UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            User user = (User) authentication.getPrincipal();
            String username = user.getUsername();
            if (username.equals(OAuth2Configuration.provider_app))
                   // Load from provider db
            else if (username.equals(OAuth2Configuration.consumer_app))
                  // Load from consumer db
            else
                throw new UsernameNotFoundException("ClientID " + username + " not found.");
        }
    };
}

UsernamePasswordAuthenticationToken is used as /oauth/token is protected with Basic Oauth using the client id and secret.

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I think you should be able to look inside SecurityContextHolder.getContext().getAuthentication. This should be an instance of OAuth2Authentication, from which you can (after you cast) call getOAuth2Request() to get the original Oauth2Request details.

With this information you can have a single UserDetailsService that can delegate lookups to the correct db tables. You could use scopes or resourceIds to help determine what db table to use.

about 4 years ago · Santiago Trujillo Denunciar

0

You could use the third option. but this is not a good principal to follow. you can send a custom param in the oauth/token end point. it can be accessed by AutoWiring HttpServletRequest in the userDetailsService.

sample postman request

UserDetailsService

@Autowired
private HttpServletRequest httpServletRequest;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    try {
        String userType = httpServletRequest.getParameter("user_type");
        LOGGER.info("Load user method \n Username : " + username + "\nuser_type : " + userType);
        if (userType == null) {
            throw new CustomOauthException("User type is required !");
        }
        if (userType.equals(String.valueOf(MOBILE_USER))) {
            //get user..

        } else if (userType.equals(String.valueOf(DRIVER))) {
            //get driver..

        } else if (userType.equals(String.valueOf(ADMIN))) {
            //get admin
        }
        throw new CustomOauthException("User type is not valid !");
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Exception : " + e.getMessage());
        throw new CustomOauthException(e.getMessage());
    }
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda