【问题标题】:How can I get the current user roles from Spring security 3.1如何从 Spring security 3.1 获取当前用户角色
【发布时间】:2012-04-22 23:41:46
【问题描述】:

我已经从数据库中为当前用户加载了角色。而且我可以在JSP中使用spring security表达式访问用户角色,并且可以隐藏没有使用hasRole授权的选项和URL。现在我想将它放在 servlet 中并将其显示在日志中(或存储在用户对象会话中)。我们如何实现它?

【问题讨论】:

    标签: spring spring-security


    【解决方案1】:

    你可以试试这样的:

    Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    

    您在权限变量中拥有角色集合。

    【讨论】:

    • 您应该使用此列表中的grantedauthority 接口,因为授权提供者之间的实现可能不同
    • 如果你这样做,会有一个未经检查的情况,但你可以通过将集合类型设置为:Collection
    【解决方案2】:

    如果您在 Java 8 上进行开发,它会变得更容易。

    获取所有用户角色:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
    Set<String> roles = authentication.getAuthorities().stream()
         .map(r -> r.getAuthority()).collect(Collectors.toSet());
    

    检查用户是否具有特定角色,例如,ROLE_USER

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
    boolean hasUserRole = authentication.getAuthorities().stream()
              .anyMatch(r -> r.getAuthority().equals("ROLE_USER"));
    

    【讨论】:

    • 我尝试了您的解决方案,但它是从 "authorties" 获取值,而不是从 "role" 获取值,我的代码是: auth.jdbcAuthentication() .dataSource(dataSource).passwordEncoder(enc) .authoritiesByUsernameQuery ("select USERNAME, role, authority from vwuserrole where USERNAME=?") .usersByUsernameQuery("select USERNAME, PASSWORD, 1 as enabled from vwuser where USERNAME=?") 我不明白应该如何操作权限和角色。
    • 好的,我在这里搜索并找到了答案:stackoverflow.com/questions/19525380/… 但是我仍然不明白为什么角色值是空的。用我提出的查询。
    【解决方案3】:

    尝试从 HttpServletRequest 调用getUserPrincipal()

    【讨论】:

    • 感谢您的回复,我没有尝试过,但我已经实现了 Dani 所说的,它对我有用。
    • 很公平。快速说明:Dani 的方法存在将您的代码与 Spring 安全实现耦合的缺点,而 getUserPricipal() 是 servlet 规范中的标准调用,应该适用于任何提供者。
    • 使用 getUserPrincipal() 你只能得到请求者的名字。我认为问题是如何获得分配给该用户的角色,所以我猜在 getUserPrincipal() 中也不会那样工作。
    • HttpServletRequest 仅适用于 Web 模块。
    【解决方案4】:

    我为我的项目创建了一个自定义 hasRole 函数。

    public static boolean hasRole (String roleName)
    {
        return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
                .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(roleName));
    }
    

    【讨论】:

      【解决方案5】:

      要完成这两个答案...

      这里是getUserPrincipal的Spring安全实现,所以可以看到getUserPrincipal其实是SecurityContextHolder

      public Principal getUserPrincipal() {
          Authentication auth = getAuthentication();
      
          if ((auth == null) || (auth.getPrincipal() == null)) {
              return null;
          }
          return auth;
      }
      
      // And the getAuthentication
      private Authentication getAuthentication() {
          Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      
          if (!trustResolver.isAnonymous(auth)) {
              return auth;
          }
          return null;
      }
      

      【讨论】:

        【解决方案6】:

        这可能对某人有所帮助。

        import org.springframework.security.core.Authentication;
        import org.springframework.web.bind.annotation.GetMapping;
        import org.springframework.ui.Model;
        import org.springframework.security.core.userdetails.User;
            
            @GetMapping("/home")
            public String getHomePage(Authentication authentication, Model model) {
                User u = (User) authentication.getPrincipal();
                model.addAttribute("cu", u);
                return "sb/homePage";
            }
        

        在模板 Thymeleaf 中:

        Current user:</br>
            <div th:if="${cu}">
                Username: [[${cu.username}]]</br>
                Password: [[${cu.password}]]</br>
                Role: [[${cu.authorities[0]}]]</br>
                Enabled: [[${cu.enabled}]]</br>
                Full: [[${cu}]]</br>
            </div>
            <div th:unless="${cu}">
                Not logged-in!
            </div>
        

        【讨论】:

          猜你喜欢
          • 2013-02-07
          • 2011-09-21
          • 1970-01-01
          • 2014-03-31
          • 2020-02-12
          • 1970-01-01
          • 2014-06-10
          • 1970-01-01
          • 2019-06-24
          相关资源
          最近更新 更多