我有两个问题,我的实体:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@Email
@NotNull
private String email;
private String password;
private boolean enabled;
@Transient
private String passwordConfirm;
@ManyToMany
@JoinTable(name = "member_role",
joinColumns = @JoinColumn(name = "member_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public boolean getEnabled() {
return enabled;
}
}
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter
private Long id;
@NotNull
@Getter
private String name;
@ManyToMany(mappedBy = "roles")
private Set<Member> members;
}
我设法创建了完整的用户CRUD并分配了角色。 现在我需要覆盖此方法以获取我的角色,然后保护我的网址
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
// List<Role> roles = roleRepository.findMemberRoles(this.member.getId());
// for(Role role : roles){
// authorities.add(new SimpleGrantedAuthority(role.getName()));
// }
authorities.add(new SimpleGrantedAuthority("ADMIN")); // just for test
authorities.add(new SimpleGrantedAuthority("test")); // just for test
return authorities;
}
问题: 1.如何将角色分配给用户 2.如果是第1点则更改getAuthorities()方法很简单。
编辑:
public class UserDetailsImpl implements UserDetails {
@Autowired
RoleRepository roleRepository;
@Autowired
MemberRepository memberRepository;
private Member member;
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public UserDetailsImpl(Member member) {
this.member = member;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
Set<Role> roles = member.getRoles(); // not
for(Role r : roles) { // working
authorities.add(new SimpleGrantedAuthority(r.getName())); // at all :)
}
//authorities.add(new SimpleGrantedAuthority("ADMIN")); // hardcoded this works
//authorities.add(new SimpleGrantedAuthority("test"));
return authorities;
}
@Override
public String getPassword() {
return member.getPassword();
}
@Override
public String getUsername() {
return member.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return member.getEnabled();
}
}