首页 > 解决方案 > How to do login for another role when User is already login as User role

问题描述

User is already login as User role and i want to do login as Employee without submitting login form but authentication gets fail,

please check the code and help me

@RequestMapping(value = "/welcome", method = RequestMethod.GET) public ModelAndView logInSucess(@RequestParam(value = "_csrf", required = false) String csrf, Map model, HttpServletRequest request, HttpServletResponse response, Principal principal) throws NormalUserNotFoundException { LOG.info("Entry :: logInSucess in controller"); User user = null;

    ModelAndView modelAndView = new ModelAndView();

    user = userDao.findById(principal.getName());

    if (user.getRole().equals(SocialNetworkingUtil.ORG_ROLE)) {

        modelAndView.setViewName("redirect:/company-home");
    } else if (user.getRole().equals(SocialNetworkingUtil.USER_ROLE)
            || user.getRole().equals(SocialNetworkingUtil.EMPLOYEE_ROLE)) {

        modelAndView.setViewName("redirect:/home");
    } else if (user.getRole().equals(SocialNetworkingUtil.SUBADMIN_ROLE)) {

        modelAndView.setViewName("redirect:/subadmin-home");
    }
    return modelAndView;

}

@RequestMapping(value = "/home") public ModelAndView userHomePage(Model model, HttpServletRequest request, HttpServletResponse response, Principal principal) throws UserNotFoundException { LOG.info("Entry :: userHomePage in controller");

    HttpSession session = request.getSession();
    session.setMaxInactiveInterval(-1);/// for user session will never expire until user is not sending logout
                                        /// request

    ModelAndView modelAndView = new ModelAndView();
    User user = userDao.findById(principal.getName());
    LOG.info(user);

    if (user.getRole().equals(SocialNetworkingUtil.USER_ROLE)) {
        NormalUser normalUser = socialNetworkingService.findUserByUsername(user.getUsername());
        session.setAttribute("username", normalUser.getEmail());
        session.setAttribute("userId", normalUser.getUserId());
        session.setAttribute("name", SocialNetworkingUtil.camelCase(normalUser.getName()));
        session.setAttribute("user", user);
        modelAndView.addObject("headerList", SocialNetworkingUtil.USER_SERVICES);
        modelAndView.setViewName("user/home");
    }

    if (user.getRole().equals(SocialNetworkingUtil.EMPLOYEE_ROLE)) {
        WorkingPlace work = workingPlaceDao.findByUserName(user.getUsername());
        NormalUser normalUser = socialNetworkingService.findUserById(work.getId());
        Company company = companyService.findById(work.getCompanyId());
        session.setAttribute("username", normalUser.getEmail());
        session.setAttribute("userId", normalUser.getUserId());
        session.setAttribute("name", SocialNetworkingUtil.camelCase(normalUser.getName()));
        session.setAttribute("workingpalce", work);
        session.setAttribute("orgType",
                SocialNetworkingUtil.SELECTED_ORGNIZATION_TYPE.PRIVATE.toString().toLowerCase());
        session.setAttribute("orgId", company.getId());
        modelAndView.setViewName("employee/home");

    }

    LOG.info("Exit :: userHomePage in controller");
    return modelAndView;

}

This is Spring controller

@RequestMapping(value = "/switch-account", method = RequestMethod.GET)
public String switchAccount(
    HttpServletRequest request,
    HttpServletResponse response,
    Principal principal) {
    LOG.info("Entry::switchAccount");

    HttpSession session = request.getSession();
    String userId = (String) session.getAttribute("userId");
    NormalUser normalUserObj = socialNetworkingService.findUserById(userId);
    //make user is not present 
    User currentLoginuser = userDao.findById(normalUserObj.getLoginUser());
    currentLoginuser.setPresent(false);
    userDao.editUser(currentLoginuser);


    User userObj = userDao.findById(normalUserObj.getWorkingEmailId());

    Authentication authRequest = new UsernamePasswordAuthenticationToken(userObj.getUsername(), userObj.getPassword());
    SecurityContextHolder.getContext().setAuthentication(authRequest);


    LOG.info("Entry::switchAccount");
    return "redirect:/welcome";
}

This is CustomUserDetailsService class

public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger LOG = Logger.getLogger(CustomUserDetailsService.class);

    @Autowired
    private UserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOG.info("Entry :: loadUserByUsername-->" + username);
        User user = getUserDetail(username);


        List<GrantedAuthority> auth=getAuthorities(user.getRole());
        org.springframework.security.core.userdetails.User userDetail;
        userDetail = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                auth);
        LOG.info(userDetail);
        LOG.info("Exit :: loadUserByUsername ");
        return userDetail;
    }


    public List<GrantedAuthority> getAuthorities(String role) {
        LOG.info("Entry :: getAuthorities--->" + role);
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        if (role.equals(SocialNetworkingUtil.USER_ROLE)) {
            authList.add(new SimpleGrantedAuthority("ROLE_USER"));

        } else if (role.equals(SocialNetworkingUtil.ORG_ROLE)) {
            authList.add(new SimpleGrantedAuthority("ROLE_ORGANISATION"));
        } else if (role.equals(SocialNetworkingUtil.SUBADMIN_ROLE)) {
            authList.add(new SimpleGrantedAuthority("ROLE_SUBADMIN"));

        }else if (role.equals(SocialNetworkingUtil.EMPLOYEE_ROLE)) {
            authList.add(new SimpleGrantedAuthority("ROLE_EMPLOYEE"));
        }
        LOG.info("Exit :: getAuthorities");
        return authList;
    }

    public User getUserDetail(String username) {
        LOG.info("Entry :: getUserDetail--------------------------------------->" + username);
        User user = userDao.findById(username);
        LOG.info(user);
        LOG.info("Exit :: getUserDetail");
        return user;
    }

}

spring security configuration file

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
    http://www.springframework.org/schema/websocket
        http://www.springframework.org/schema/websocket/spring-websocket.xsd">


    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/home*" access="hasAnyRole('ROLE_USER','ROLE_EMPLOYEE')" />
        <intercept-url pattern="/company-home*" access="hasRole('ROLE_ORGANISATION')" />
        <intercept-url pattern="/subadmin-home*" access="hasRole('ROLE_SUBADMIN')" /> 

        <!--for web socket chat security -->
        <intercept-url pattern="/ws/**" access="permitAll" />
        <intercept-url pattern="/app/**" access="permitAll" />
        <intercept-url pattern="/topic/**" access="permitAll" />
        <intercept-url pattern="/topic/ws/*" access="permitAll" />
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/ws*" access="isAuthenticated()" />

        <!-- hasRole('ROLE_ADMIN') -->
        <intercept-url pattern="/chatprivate*" access="isAuthenticated()" />
        <intercept-url pattern="/topic/wsresponse" access="isAuthenticated()" />

        <form-login login-page="/login" default-target-url="/welcome"
            authentication-failure-url="/"></form-login>


        <logout logout-url="/logout" logout-success-url="/signout"
            invalidate-session="false" />


        <session-management session-fixation-protection="migrateSession"
            invalid-session-url="/"
            session-authentication-error-url="/login-error?authFailed=true">


            <concurrency-control max-sessions="1"
                expired-url="/Timeout?timeout=true" session-registry-alias="sessionRegistry" />
        </session-management>



        <csrf disabled="true"/>
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder ref="encoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>



    <beans:bean id="userDetailsService"
        class="com.social.portal.service.CustomUserDetailsService" />

    <beans:bean id="encoder"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

    <beans:bean id="sessionRegistry"
        class="org.springframework.security.core.session.SessionRegistryImpl" />

</beans:beans>

标签: spring-mvcspring-security

解决方案


更改您的代码以在authRequest Authentication令牌中具有权限,如下所示;

List<GrantedAuthority> auths = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"), 
                                           new SimpleGrantedAuthority("ROLE_EMPLOYEE"));

Authentication authRequest = new UsernamePasswordAuthenticationToken(userObj.getUsername(), userObj.getPassword(), auths);

推荐阅读