[英]Spring Security - How to get the roles assigned to user
我正在實施 JWT 基於角色的授權。 我正在通過 postman 測試我的 api。
用戶首先發出POST
請求並在我們傳入名字、empid 和密碼的地方注冊自己。 成功注冊的用戶返回一個響應,其中包括一個列roles
,該列角色在開始時為null
。 然后我手動分配用戶角色。 我的ROLE
表中有兩個角色,即我手動分配的 ADMIN 或 USER。
在此之后,用戶需要進行身份驗證或登錄才能生成令牌。
到目前為止,一切都是正確的。 令牌正在生成,但它返回我的角色值 null 即使我手動分配了用戶 ADMIN 角色。 如何獲取分配給用戶的角色? 請幫忙。 我在下面粘貼一些代碼:
下面是我的 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());
它似乎沒有做任何事情。 我還缺少什么?
用戶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;
您需要在 UserDetailsWithToken 中設置角色,以在響應 object 中獲取它們。 它們僅在 JWT object 上設置。
獲取角色列表后,只需將以下行添加到您的 AuthenticationController
UserDetailsWithToken.setRoles(roles);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.