我有 4 种不同类型的用户。每种类型都有自己的角色和附加属性。 用户是父级,还有 3 个继承者。
我还使用 Spring Data。
我可以通过什么方式实现 UserDetailsService 来使用 4 种不同类型的用户?
现在我有:
@Inheritance(strategy = InheritanceType.JOINED)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
private String email;
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
}
和
public class Employee extends User implements Serializable {
private static final long serialVersionUID = 1L;
private String fullName;
@ManyToMany(mappedBy = "employees")
private Set<Project> projects;
@OneToMany(mappedBy = "employee")
private Set<Task> tasks;
}
还有其他。
最佳答案
既然您正在谈论UserDetailsService
,我假设您使用Spring Security
。如果您只需要对用户进行身份验证/授权,我不确定您是否需要 UserDetailsService 提供的完整用户管理。定义一个 AuthenticationProvider
并在此处进行查询可能就足够了
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@PersistenceContext
private EntityManager entityManager;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new AuthenticationProvider() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// Do you database query here
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_")); // list of roles from database
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
authentication.getCredentials(), authorities);
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
})
}
}
这个示例是内联的,您可能应该将 AuthenticationProvider
设为一个真正的类。
使用未经身份验证的Authentication
调用AuthenticationProvider
,该身份验证是由过滤器(通常是BasicAuthenticationFilter
或UsernamePasswordAuthenticationFilter
)创建的。此后,Authentication
被提供给 ProviderManager
,后者询问每个 AuthenticationProvider
是否可以验证这种类型的 Authentication
(这就是 supports() 方法的用途)。找到合适的 AuthenticationProvider
后,系统会要求其进行身份验证 - 您可以在此处进行数据库查找并从数据库中查找角色,并根据数据库中的角色使用 GrantedAuthorities
列表构建新的 Authentication
。
请注意,您应该将“ROLE_”放在角色前面(除非您像这样存储它们),否则它将无法与使用 HttpSecurity
配置的声明性访问一起使用
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/home").permitAll()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
// more lines
}
此处 ADMIN 映射到 GrantedAuthority
ROLE_ADMIN。
关于java - 使用 Spring Security 的多个用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41535893/