29

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

4

6 回答 6

75

你可以尝试这样的事情:

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

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

于 2012-04-10T17:15:09.697 回答
35

如果您在 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"));
于 2017-03-21T21:17:58.550 回答
7

尝试从 HttpServletRequest调用getUserPrincipal() 。

于 2012-04-10T17:11:07.717 回答
4

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

public static boolean hasRole (String roleName)
{
    return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(roleName));
}
于 2018-06-23T09:38:23.110 回答
2

要完成这两个答案...

这是 Spring 的安全实现getUserPrincipal,因此您可以看到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;
}
于 2016-11-19T14:02:11.443 回答
0

这可能会帮助某人。

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>
于 2021-11-18T18:57:01.827 回答