在Spring Security中获取用户角色的最佳方式



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

  1. 方法1-使用以下代码创建辅助类:SecurityContextHolder.getContext((.getAuthentication((.getAuthorities((.stream((.anyMatch(grantedAuthority->grantedAuthority.getAuthority((.equals(roleName((
  2. 方法2-将HttpServlet请求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在评论中的回答:

这不是你喜欢哪一个,你需要哪一个!你需要检查控制器之外的用户角色吗?如果是,那么你使用第一种是正确的,但如果你不需要控制器之外的,第二种方法是更快的

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

最新更新