2017-08-07 76 views
-1

我想單擊註銷按鈕後獲取用戶角色。 如果角色是管理員我必須在/註銷返回/login.jsp
如果角色是用戶我必須在/註銷提前返回/index.jsp
如何在spring security和java註銷後獲取用戶角色?

感謝

我controller.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(); 
    } 

回答

-1

您可以通過以下

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

得到控制Authentication對象,然後你可以通過調用下面的方法獲得的登錄用戶的角色

authentication.getAuthorities(); 
0

您應該實施自定義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" /> 
相關問題