【发布时间】:2012-04-22 23:41:46
【问题描述】:
我已经从数据库中为当前用户加载了角色。而且我可以在JSP中使用spring security表达式访问用户角色,并且可以隐藏没有使用hasRole授权的选项和URL。现在我想将它放在 servlet 中并将其显示在日志中(或存储在用户对象会话中)。我们如何实现它?
【问题讨论】:
我已经从数据库中为当前用户加载了角色。而且我可以在JSP中使用spring security表达式访问用户角色,并且可以隐藏没有使用hasRole授权的选项和URL。现在我想将它放在 servlet 中并将其显示在日志中(或存储在用户对象会话中)。我们如何实现它?
【问题讨论】:
你可以试试这样的:
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
您在权限变量中拥有角色集合。
【讨论】:
如果您在 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"));
【讨论】:
尝试从 HttpServletRequest 调用getUserPrincipal()。
【讨论】:
我为我的项目创建了一个自定义 hasRole 函数。
public static boolean hasRole (String roleName)
{
return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(roleName));
}
【讨论】:
要完成这两个答案...
这里是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;
}
【讨论】:
这可能对某人有所帮助。
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>
【讨论】: