简体   繁体   English

如何使用 Spring Security 获取用户在我的控制器中登录的角色

[英]How to get the role that a user logged in with in my controller using Spring Security

I am trying to implement Spring security features for authorization and authentication.我正在尝试为授权和身份验证实现 Spring 安全功能。 I am facing some issues regarding user roles.我正面临一些有关用户角色的问题。 I want the role the user has logged in with to be checked in my controller, so that on the basis of the role I can redirect the user to the respective page (as a user canhave more than one role).我希望在我的控制器中检查用户登录的角色,以便根据角色将用户重定向到相应的页面(因为用户可以拥有多个角色)。 However, I am not getting the logged in role in my Java controller.但是,我没有在我的 Java 控制器中获得登录角色。

login jsp page登录jsp页面

   <form action="<c:url value='j_spring_security_check'/>"
                method="POST" name='loginForm'>
 <table class="center">
 <tr><td>User Name:  </td><td><input type="text" name="j_username"  id="userName" ></td></tr>
 <tr><td>Password:  </td><td><input type="password" name="j_password" id="password"></td></tr> 
 <tr><td>Role: </td><td>
 <select id="role" name="j_role">  
 <option style="font-weight: bold;">Select Roll </option>
 <option id="role1" value="role1">Role 1</option>
 <option id="role2" value="role2">Role 2 </option>
 <option id="role3" value="role3">Role 3 </option>
 </select></td></tr>

 <tr><td><input type="submit" value="Login" style="height: 25px; width: 100px"></td><td><input type="reset" value="Reset" style="height: 25px; width: 100px"></td></tr>
 <tr><td colspan=2>&nbsp;</td></tr>

  <tr><td colspan=2></td></tr>
 </table>
 </form>

Controller code :控制器代码:

@RequestMapping(value="/home", method = RequestMethod.GET)
 public ModelAndView printWelcome(ModelMap model, Principal principal ) throws SQLException {

     ModelAndView mav = new ModelAndView(); 
try{
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     String n= auth.getName();
    String r= auth.getAuthorities().toString();

     System.out.println("the value of username is "+n);
    System.out.println("the value of role is  "+r);

     returning result
  } 
}

Here I am getting which user has logged in and also I'm retrieving their roles, as defined in my spring-security.xml file - eg [role1 , role2].在这里,我获取了哪个用户已登录,并且我正在检索他们的角色,如我的 spring-security.xml 文件中所定义的 - 例如 [role1 , role2]。 This doesn't retrieve the role by which user has logged in with.这不会检索用户登录时使用的角色。 Through the user name that the user has logged in with I then get the role from the database and redirect to the respective page.通过用户登录的用户名,然后我从数据库中获取角色并重定向到相应的页面。 It works fine if user has only one role, but if they have more than one role then I am not clear how I will redirect them.如果用户只有一个角色,它工作正常,但如果他们有多个角色,那么我不清楚我将如何重定向他们。 So, I thought once logged in the user can select role and on that basis I will redirect.所以,我认为一旦登录用户可以选择角色,并在此基础上我将重定向。

Spring-Security.xml Spring-Security.xml

   <http auto-config="true"  use-expressions="true">
 <intercept-url pattern="/home" access="hasAnyRole('role1','role2','role3')"/>

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


</http>
<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <user-service>

            <user name="user1" password="123" authorities="role1,role2" />   
      <user name="user2" password="123" authorities="role2,role3" />   
            <user name="stephen" password="123" authorities="role1" />
            <user name="robert" password="123" authorities="role3" />
        </user-service>
    </authentication-provider>
</authentication-manager>

Each role has different view pages, so if I login with user1 and from dropdown I select role2 how will I get this role2 in my controller so that I can redirect the user1 to respective jsp page?每个角色都有不同的视图页面,所以如果我使用 user1 登录并从下拉列表中选择 role2 我将如何在我的控制器中获得这个 role2,以便我可以将 user1 重定向到相应的 jsp 页面?

If there is a better way to achieve this please let me know.如果有更好的方法来实现这一点,请告诉我。

Inject an Authentication into your Controller, rather than Principal .Authentication注入您的 Controller 而不是Principal

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

authentication.getAuthorities(); will now return your roles.现在将返回您的角色。

This is my solution in controller.这是我在控制器中的解决方案。 My project there are two pages default.我的项目默认有两个页面。 A page is welcome, and other page default is a dashboard where access only if the user contain role ROLE DASHBOARD.一个页面是受欢迎的,其他页面默认是一个仪表板,只有当用户包含角色 ROLE DASHBOARD 时才能访问。

@RequestMapping(value="/redirectToPageDefault",method=RequestMethod.GET)
public ModelAndView redirectToPageDefault(SecurityContextHolder auth){
    Collection<?extends GrantedAuthority> granted = auth.getContext().getAuthentication().getAuthorities();
    String role;
    //set page default to rules common
    ModelAndView mav = new ModelAndView("empty");
    for(int i=0;i<granted.size();i++){
        role = granted.toArray()[i] + "";
        logger.info("role verified" + i + " is -> " + role);
        //verify if user contain role to view dashboard page default
        if(role.equals("ROLE_DASHBOARD")){
            logger.warn("IDENTIFIED: ROLE_DASHBOARD = " + role );
            mav.setViewName("dasboard");
        }               
    }   
    return mav;
}

Try one of the below 2:尝试以下 2 项之一:
1. Pass java.security.Principal to any of your Controller methods. 1. 将 java.security.Principal 传递给您的任何 Controller 方法。
2. Get logged in user via SecurityContextHolder.getContext().getAuthentication() 2. 通过 SecurityContextHolder.getContext().getAuthentication() 获取登录用户

You can ckeck the roles by this method您可以通过此方法检查角色

private boolean hasRole(String role) {
  Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>)
  SecurityContextHolder.getContext().getAuthentication().getAuthorities();
  boolean hasRole = false;
  for (GrantedAuthority authority : authorities) {
     hasRole = authority.getAuthority().equals(role);
     if (hasRole) {
      break;
     }
  }
  return hasRole;
}  

Also you can see this article: How to Access Roles and User Details Using Spring Security您也可以看到这篇文章: 如何使用 Spring Security 访问角色和用户详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM