【问题标题】:Optimal way of getting user roles in Spring Security在 Spring Security 中获取用户角色的最佳方式
【发布时间】:2020-06-23 05:25:23
【问题描述】:

我需要检查控制器中的用户权限,以决定将哪些参数列表发送到视图。 我知道我可以通过两种方式检查特定用户是否具有特定角色:

  1. 方法 1 - 使用以下代码创建辅助类: SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream() .anyMatch(grantedAuthority ->grantedAuthority.getAuthority().equals(roleName));
  2. 方法二 - 将 HttpServletRequest req 添加到控制器,然后 req.isUserInRole("ROLE_ADMIN")

但是哪种方式最好呢?至于我,我认为第一个更有用,因为我可以在控制器外部将它用于内部目的。

    @RequestMapping(value = "/goal/edit/{id}", method = RequestMethod.GET)
    public String edit (@PathVariable Long id, Model model, RedirectAttributes redirect, HttpServletRequest req) {
        Goal goal = goalService.getById(id);

        //Method 1 
        User user = AuthUtils.getCurrentUser();

        //Medhod 2
        Boolean is_admin = req.isUserInRole("ROLE_ADMIN");

        Iterable<Role> roles = null;

        if (is_admin==true) {
            roles = roleService.getAll();
            }
            else roles = user.getRoles();

        model.addAttribute("goal", goal);
        model.addAttribute("roles", roles);
        return "goal_form";
    }

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

【问题讨论】:

  • 这不是你喜欢哪一个,你需要哪一个!如果是,您是否需要检查控制器外部的用户角色,那么您可以使用第一个,但如果您在控制器之外不需要它,则第二种方法更快
  • @AMA 谢谢。

标签: java spring-security


【解决方案1】:

作为AMA's answers in a comment:

这不是你喜欢哪一个,你需要哪一个! 如果是,您是否需要检查控制器外部的用户角色,那么您可以使用第一个,但如果您在控制器外部不需要它,则第二种方法更快

我需要检查控制器之外的用户角色,我将使用第一方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2012-04-22
    • 2012-01-16
    • 2018-01-14
    • 1970-01-01
    • 2011-07-21
    • 2016-12-15
    相关资源
    最近更新 更多