【问题标题】:Spring Security - How to get the roles assigned to userSpring Security - 如何获取分配给用户的角色
【发布时间】:2025-12-08 14:45:02
【问题描述】:

我正在实施 JWT 基于角色的授权。我正在通过邮递员测试我的 api。

用户首先发出POST 请求并在我们传入名字、empid 和密码的地方注册自己。成功注册的用户返回一个响应,其中包括一列roles,它的开头是null。然后我手动分配用户角色。我在 myROLE 表中有两个角色,即我手动分配的 ADMIN 或 USER。

在此之后,用户需要进行身份验证或登录才能生成令牌。

到目前为止,一切都是正确的。正在生成令牌,但即使我手动分配了用户 ADMIN 角色,它也会返回角色值 null 。如何获取分配给用户的角色?请帮忙。我在下面粘贴一些代码:

下面是我的用户认证api:AuthenticationController

    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                authenticationRequest.getEmpID(),
                authenticationRequest.getPswd()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);
    
    final String token = jwtTokenUtil.generateToken(userDetails 
      ,authentication);


    List<String> roles = authentication.getAuthorities().stream()
    .map(item -> item.getAuthority())
    .collect(Collectors.toList()); 

      

正如您在此处看到的,我已经定义了角色。验证用户时如何获取角色?

我如上所述添加了这个:

 List<String> roles = authentication.getAuthorities().stream()
    .map(item -> item.getAuthority())
    .collect(Collectors.toList()); 

它似乎没有做任何事情。我还缺少什么?

Users.java:

public class Users {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private Long id;

//其他栏目

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "CONFIG_USERROLE", joinColumns = @JoinColumn(name = 
"USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
private Set<Role> roles; 

public Users(){

}

角色.java:

 public class Role {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ROLE_ID")
private Long id;

@Column(name = "ROLE")
private String role;

【问题讨论】:

  • 您能否发布手动分配 ADMIN 角色以及用户实体的代码?角色分配行是否在数据库中?
  • @DrGodCarl 请查看我更新的问题。

标签: java spring-boot spring-security jwt


【解决方案1】:

您需要在您的 UserDetailsWithToken 中设置角色以在响应对象上获取它们。它们仅在 JWT 对象上设置。

获取角色列表后,只需将以下行添加到您的 AuthenticationController 中

UserDetailsWithToken.setRoles(roles);

【讨论】:

  • 嗨。这正是我所缺少的。现在可以了。非常感谢!
  • 您需要填充整个对象,您只是在设置令牌。