[英]Multiple users with Spring Security
我有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
調用Authentication
,該Authentication
由過濾器創建,通常為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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.