Spring Security – 如何获取分配给用户的角色

huangapple go评论96阅读模式
英文:

Spring Security - How to get the roles assigned to user

问题

我正在实施基于JWT的角色授权。我正在通过Postman测试我的API。

用户首先发出“POST”请求并在其中注册,我们传递名字,员工ID和密码。用户成功注册后,返回一个响应,包括一个名为“roles”的列,初始值为“null”。然后,我手动分配用户角色。我的“ROLE”表中有两个角色,即ADMIN或USER,我手动分配它们。

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

到目前为止,一切都正确。令牌已生成,但尽管我手动分配了用户ADMIN角色,但它仍然返回roles的值为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;
}
英文:

I am implementing JWT Role Based Authorization. I am testing my apis through postman.

The users first makes a POST request and registers itself where we pass in the firstname, empid and password. The user on successfull registarion returns a response including a column roles which is null in the starting. Then I manually assign the user role. I have two roles in myROLE table i.e ADMIN or USER which I assign them manually.

After this, the user needs to authenticate or sign in in order for the token to be gnenrated.

Upto this point everything is correct. The token is being generated but it returns me the roles values null even though I have assigned the user ADMIN role manually. How do I get the roles assigned to user? please help. I am pasting some code below:

Below is my api for user authentication : AuthenticationController

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


	List&lt;String&gt; roles = authentication.getAuthorities().stream()
	.map(item -&gt; item.getAuthority())
	.collect(Collectors.toList()); 

As you can see here I have roles defined. How do I get the roles when authenticating the user?

I added this as mentioned above:

 List&lt;String&gt; roles = authentication.getAuthorities().stream()
	.map(item -&gt; item.getAuthority())
	.collect(Collectors.toList()); 

It does not seem to do anything. What else I am missing?

Users.java:

public class Users {

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

//other columns

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = &quot;CONFIG_USERROLE&quot;, joinColumns = @JoinColumn(name = 
&quot;USER_ID&quot;), inverseJoinColumns = @JoinColumn(name = &quot;ROLE_ID&quot;))
private Set&lt;Role&gt; roles; 

public Users(){

}

Role.java:

 public class Role {

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

@Column(name = &quot;ROLE&quot;)
private String role;

答案1

得分: 0

只需将以下行添加到AuthenticationController中,在获取角色列表后,将其设置到UserDetailsWithToken对象中:

UserDetailsWithToken.setRoles(roles);
英文:

You need to set the roles in your UserDetailsWithToken to get them on the response object. They are only set on the JWT object.

Just add the following line to your AuthenticationController, after obtaining the roles list

UserDetailsWithToken.setRoles(roles);

huangapple
  • 本文由 发表于 2020年8月11日 00:05:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63343820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定