我正在实现JWT基于角色的授权。我正在通过邮递员测试我的api。
用户首先发出POST
请求,并在我们将其输入名字,空号和密码的位置进行注册。成功注册的用户返回一个响应,该响应包括一列roles
,该列的开头是null
。然后,我手动分配用户角色。我的ROLE
表中有两个角色,即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(){
}
Role.java:
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ROLE_ID")
private Long id;
@Column(name = "ROLE")
private String role;
答案 0 :(得分:0)
您需要在UserDetailsWithToken中设置角色,以使其在响应对象上。它们仅在JWT对象上设置。
在获取角色列表之后,只需将以下行添加到您的AuthenticationController中
UserDetailsWithToken.setRoles(roles);