[英]Optimal way of getting user roles in Spring Security
我需要檢查我的控制器中的用戶權限,以確定將哪些參數列表發送到視圖。 我知道我可以通過兩種方式檢查特定用戶是否具有特定角色:
但哪種方式最好? 至於我,我認為第一個更有用,因為我可以在控制器外部將它用於內部目的。
@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 在評論中的回答:
不是你喜歡哪一種,你需要哪一種! 如果是,您是否需要檢查控制器外的用戶角色,那么您使用第一個是正確的,但如果您在控制器外不需要它,則第二種方式更快
我需要檢查控制器之外的用戶角色我將使用第一種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.