Search code examples
springspring-bootspring-securityspring-security-oauth2spring-oauth2

Multiple Login endpoints Spring Security OAuth2


I'm trying to implement multiple login strategies for different user roles (Spring Security OAuth2 with Spring Boot 2), and each strategy should use a different endpoint. I have 3 user types, REGULAR, EXTERNAL, CLIENT, where regular logs in vía username/password, external logs in via documentId/key, and client does some SMS shenanigans before to acquire the current password, and it logs with phone/password. They can already log in from a regular website, but they'll have mobile applications for each role.

I've tried to create multiple AuthorizationServer instances with @EnableAuthorizationServer, each one with the config, but it only picks up the last one. Each role has a different UserDetailsService impl, and exactly one app created in the DB. I wanted to expose them so that client apps use /client/oauth/..., regular apps use /regular/oauth/... and external apps use /external/oauth/... How can I achieve this?


Solution

  • If you are using the spring security and oauth2 and you want to get many different login endpoint you may need to custom AuthenticationEntryPoint.

    @Component
    public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
        private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
            String clientId = request.getParameter("client_id");
            String redirectUrl = "/login";
            HttpSession session = request.getSession();
            session.setAttribute(SessionSaveAttribute.CLIENT_ID_ATR, clientId);
            //echoSessionAtr(request);
            redirectStrategy.sendRedirect(request, response, redirectUrl);
        }
    
    }
    

    So you may can can custom the login endpoint by make your condition.

    if(clientId=="REGULAR_CLIENT_ID"){
        redirectUrl = "regular/login"
    } else if(clientId=="SPECIAL_CLIENT_ID"){
        redirctUrl = "...";
    }