Linux 拨号vps windows公众号手机端

spring中security怎么获取当前用户

lewis 8年前 (2017-08-08) 阅读数 7 #程序编程
文章标签 securityspring

在Spring Security中,可以通过以下方式来获取当前用户:

  1. 通过SecurityContextHolder获取当前认证的Authentication对象,然后通过Authentication对象获取当前用户的Principal(主体)信息。
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
    Object principal = authentication.getPrincipal();
    if (principal instanceof UserDetails) {
        String username = ((UserDetails)principal).getUsername();
    } else {
        String username = principal.toString();
    }
}
  1. 在Controller层中,可以使用@AuthenticationPrincipal注解将当前用户作为方法参数直接注入。
@GetMapping("/user")
public String getUserInfo(@AuthenticationPrincipal UserDetails userDetails) {
    String username = userDetails.getUsername();
    // ...
}
  1. 使用SecurityExpressionMethods提供的hasRole、hasAuthority等方法判断当前用户是否具有指定的角色或权限。
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void someMethod() {
    // ...
}

需要注意的是,以上方法仅适用于已经通过认证的用户。如果用户未认证或未登录,以上方法将无法获取到当前用户信息。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门