Spring Security Authentication with different type of users

921 Views Asked by At

i am new to spring security and i am building an web application in which i have 4 different roles i understand that spring use different roles to authorized user but how can i implement it when there are 4 different type of sign up and after sign in i have to send user to 4 different pages like if a user enter as admin i want to send him to admin page if its a customer i want to send him to customer page .

so far i am able to use user detail service to authenticate a single user .

3

There are 3 best solutions below

0
On

In addition to shi's response, I would make some changes in the Handler. You could use a Map<String,String> as class field in the handler to manage the role-redirections matchings.

And you could also extend org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler to take advantage of it's already implemented methods, this way:

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

public class MySimpleUrlAuthenticationSuccessHandler 
        extends SimpleUrlAuthenticationSuccessHandler 
        implements AuthenticationSuccessHandler {

    protected Logger logger = Logger.getLogger(this.getClass());

    private Map<String, String> authorityRedirectionMap;

    public MySimpleUrlAuthenticationSuccessHandler(Map<String, String> authorityRedirectionMap) {
        super();
        this.authorityRedirectionMap = authorityRedirectionMap;
    }

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        String targetUrl = determineTargetUrl(request, response, authentication);

        if (response.isCommitted()) {
            logger.debug("Response has already been committed. Unable to redirect to "
                    + targetUrl);
            return;
        }

        this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }

    /**
     * 
     * @param request
     * @param response
     * @param authentication
     * @return
     */
    protected String determineTargetUrl(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication) {
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if(this.authorityRedirectionMap.containsKey(grantedAuthority.getAuthority())){
                return this.authorityRedirectionMap.get(grantedAuthority.getAuthority());
            }
        }
        return super.determineTargetUrl(request, response);     
    }

}

Your configuration xml's success handler section should be like this:

<beans:bean id="myAuthenticationSuccessHandler"
            class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler">
    <beans:constructor-arg>
        <beans:map>
            <beans:entry key="ROLE_USER" value="/user.html" />              
            <beans:entry key="ROLE_ADMIN" value="/admin.html" />            
            <beans:entry key="ROLE_CUSTOMER" value="/customer.html" />              
            <beans:entry key="ROLE_OTHER" value="/other.html" />            
        </beans:map>    
    </beans:constructor-arg>    
    <beans:property name="defaultTargetUrl" value="/default.html" />
</beans:bean>
0
On

In your configuration define four types of roles and add a custom login success handler. see below as example.

<http use-expressions="true">
    <intercept-url pattern="/login*" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>

    <form-login login-page='/login.html'
                authentication-failure-url="/login.html?error=true"
                authentication-success-handler-ref="myAuthenticationSuccessHandler"/>

    <logout/>
</http>

<authentication-manager>
<authentication-provider>
    <user-service>
        <user name="user1" password="user1Pass" authorities="ROLE_USER"/>
        <user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN"/>
        <user name="customer1" password="customer1Pass" authorities="ROLE_CUSTOMER"/>
        <user name="other1" password="other1Pass" authorities="ROLE_OTHER"/>
    </user-service>
</authentication-provider>
</authentication-manager>

<beans:bean id="myAuthenticationSuccessHandler"
            class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>  

And AuthenticationSuccessHandler goes like this:

public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    protected Log logger = LogFactory.getLog(this.getClass());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException {

        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }

    protected void handle(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException {

        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            logger.debug(
              "Response has already been committed. Unable to redirect to "
              + targetUrl);
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        boolean isUser = false;
        boolean isAdmin = false;
    boolean isCustomer = false;
    boolean isOther = false;
        Collection<? extends GrantedAuthority> authorities
         = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                isUser = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_CUSTOMER")) {
                isCustomer = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_OTHER")) {
                isOther = true;
                break;
            }
        }

        if (isUser) {
            return "/user.html";
        } else if (isAdmin) {
            return "/admin.html";
        } else if (isCustomer) {
            return "/customer.html";
        } else if (isOther) {
            return "/other.html";
        } else {
            throw new IllegalStateException();
        }
    }

    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}
0
On

Another alternative is redirecting your successfull login page authentication-success-handler-ref to special controller mapping.

@RequestMapping("/login/process")
public String processLogin() {
  Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>)
    SecurityContextHolder.getContext().getAuthentication().getAuthorities();

  if (authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
    return "redirect:/admin-page";
  } else if (authorities.contains(new SimpleGrantedAuthority("ROLE_USER_1"))) {
    return "redirect:/user_1";
  } else if (authorities.contains(new SimpleGrantedAuthority("ROLE_USER_2"))) {
    return "redirect:/user_2";
  } else if (authorities.contains(new SimpleGrantedAuthority("ROLE_USER_3"))) {
    return "redirect:/user_3";
  }
  // catch else
  return "redirect:/";
}