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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29100487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:41:28  来源:igfitidea点击:

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

javaspringspring-mvcauthenticationspring-security

提问by user07

I am trying to implement Spring security features for authorization and authentication. 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.

我正在尝试为授权和身份验证实现 Spring 安全功能。我正面临一些有关用户角色的问题。我希望在我的控制器中检查用户登录的角色,以便根据角色将用户重定向到相应的页面(因为用户可以拥有多个角色)。但是,我没有在我的 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 - e.g. [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 文件中定义的角色 - 例如 [role1 , role2]。这不会检索用户登录时使用的角色。通过用户登录的用户名,然后我从数据库中获取角色并重定向到相应的页面。如果用户只有一个角色,它工作正常,但如果他们有多个角色,那么我不清楚我将如何重定向他们。所以,我认为一旦登录用户就可以选择角色,并在此基础上我将重定向。

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.

如果有更好的方法来实现这一点,请告诉我。

回答by David Lavender

Inject an Authenticationinto your Controller, rather than Principal.

将 anAuthentication注入您的控制器,而不是Principal.

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

authentication.getAuthorities();will now return your roles.

authentication.getAuthorities();现在将返回您的角色。

回答by Luis Camargo

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;
}

回答by zoostar

Try one of the below 2:
1. Pass java.security.Principal to any of your Controller methods.
2. Get logged in user via SecurityContextHolder.getContext().getAuthentication()

尝试以下 2 项之一:
1. 将 java.security.Principal 传递给您的任何 Controller 方法。
2. 通过 SecurityContextHolder.getContext().getAuthentication() 获取登录用户