【问题标题】:how to get the user role after logout in spring security and java?如何在spring security和java中注销后获取用户角色?
【发布时间】:2018-01-14 10:03:21
【问题描述】:

我想在单击注销按钮后获取用户角色。 如果角色是 admin 我必须在 /logout 中返回 /login.jsp
如果角色是 user 我必须在 /logout 中返回 /index.jsp

提前致谢

我的控制器.java:

 @RequestMapping(value="/logout",method=RequestMethod.GET)
        public String logout(HttpServletRequest request,ModelMap model)
        {
    model.addAttribute("userForms",userService.getActiveUserList());
      model.addAttribute("Success",true);
      return "/login";
        }

UserService.java

public List<UserForm> getActiveUserList() 
{
        List<UserForm> userForms = new ArrayList<UserForm>();

        List<User> users = new ArrayList<User>();

        users = userDAO.getActiveList();

        for (User user : users) {

            String crmDomainLink=crmProperties.getProperty("CRMAppDomain");
            UserForm userForm = new UserForm(
                    user.getUserId(),user.getName(), user.getCode(),
CRMConstants.convertUSAFormatWithTime(user.getCreatedDateTime()),
 user.getIsEnabled(), null);
            userForms.add(userForm);
        }

        return userForms;
    }

MyDAO.java

public List<User> getActiveList() {
return this.sessionFactory.getCurrentSession().createCriteria(User.class).add(Restrictions.and(Restrictions.eq("isEnabled", 1),Restrictions.ne("userId", 1))).list();
    }

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    您应该实现自定义LogoutSuccessHandler。比如:

    @Component
    public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            if (AuthorityUtils.authorityListToSet(authentication.getAuthorities()).contains("ROLE_ADMIN")) {
                response.sendRedirect("/login.jsp");
            } else {
                response.sendRedirect("/index.jsp");
            }
        }
    }
    

    将其添加到安全配置中,如果是 XML:

    <logout success-handler-ref="customLogoutSuccessHandler" />
    

    【讨论】:

      【解决方案2】:

      您可以通过以下方式在控制器中获取Authentication对象

      @RequestMapping(value="/logout", method = RequestMethod.GET)
      public String logout(ModelMap model, Authentication authentication) {
      }
      

      然后就可以调用下面的方法获取登录用户的角色了

      authentication.getAuthorities();
      

      【讨论】:

        猜你喜欢
        • 2021-12-19
        • 2012-11-10
        • 1970-01-01
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        • 2013-02-07
        • 2018-06-22
        • 2011-09-21
        相关资源
        最近更新 更多