2017-01-08 12 views
1

私は4種類のユーザーを持っています。すべてのタイプには独自の役割と追加属性があります。 ユーザーは親であり、継承者は3人です。複数のユーザー(スプリングセキュリティあり)

また、私はSpring Dataを使用します。

どのようにして4つの異なるタイプのユーザーを使用するためにUserDetailsS​​erviceを実装できますか?

今私が持っている:

@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; 

} 

そして、他。

答えて

0

あなたは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実際のクラスにする必要があります。

AuthenticationProviderは、典型的にBasicAuthenticationFilter又はUsernamePasswordAuthenticationFilter、フィルタによって作成された未認証Authentication、と呼ばれています。この後、AuthenticationProviderManagerに与えられ、AuthenticationProviderのそれぞれにこのタイプのAuthenticationを認証できるかどうかを尋ねます(これはが対応しています)の方法です)。適切なAuthenticationProviderが見つかると、認証が求められます。これはデータベース参照を行い、データベースからロールを見つけてデータベースのロールに基づいてGrantedAuthoritiesというリストを持つ新しいAuthenticationを構築します。

それ以外の場合は、宣言型のアクセスはこちらをADMINマップをHttpSecurity

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests() 
     .antMatchers("/","/home").permitAll() 
     .antMatchers("/admin/**").access("hasRole('ADMIN')") 
     // more lines 
} 

を使用して設定では動作しません、(あなたがそのようにそれらを保存しない限り)あなたは役割の前で「ROLE_」を置く必要があることに注意してくださいGrantedAuthority ROLE_ADMIN

関連する問題