我想将角色视为用户的属性,而不是拥有独立的角色类,因此我无需在数据库中有角色表。但是一般的spring UserDetails
服务会传递GrantedAuthority
(即Collection<GrantedAuthority> getAuthorities())
作为用户详细信息参数之一)。
我想做的就是用在“用户”类中声明的角色(字符串角色)替换此通用GrantedAuthority
参数,如下所示。
@Entity(name="usr")
public class User {
@Id
@Column(unique=true)
private String username;
private String password;
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
还有我的customUserdetail服务类:
@Service
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
x.y.User user = repository.findByUsername(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(
user.getUsername(),
user.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
user.getRole());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
自从我传递了
user.getRole()
(它是String)而不是Collection<GrantedAuthority> getAuthorities()
(这是Spring安全中的默认角色类型)以来,它返回一个错误。如何自定义它,以便可以使用已声明为“用户”类的属性的角色(字符串类型)?
Mind:
必须保留正常的安全流程!。含义,而不会影响正常的弹簧安全流程。先感谢您!。
最佳答案
可以通过您的User实体实现UserDetails接口并覆盖getAuthorities()方法来完成此操作:
public class User implements UserDetails {
...
private String role;
...
@Override
public Set<GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(this.role));
return authorities;
}
}
而且最好保持角色名称的Spring Security命名约定,即以“ROLE_”前缀开头。