2016-05-04 5 views
1

このコード私は認証できるデータベースからユーザを追加するのに使用しますが、このコードは一度実行されると問題はどのようにして登録できますか? 私はこの解決策を持っていますHow to adding new user to Spring Security in runtimeしかし私はそれを私の実際のコードに追加して助けてください。 これはあなたが単に別のauthenticationProviderを設定することができます私のコードSpringでユーザを動的に追加するJava

@Configuration 
    @EnableWebSecurity 
    protected static class SecurityConfig extends WebSecurityConfigurerAdapter { 
     @Autowired 
     DataSource dataSource; 

     @Autowired 
     UserRepository userRepository; 

     @Override 
     protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
      for (UsersEntity user : userRepository.findAll()) 
       if (user.getUsername() != null && user.getPassword() != null) 
        auth. 
          inMemoryAuthentication() 
          .passwordEncoder(UsersEntity.ENCODE_PASS) 
          .withUser(user.getUsername()).password(user.getPassword()) 
          .roles("USER"); 
     } 


     @Bean 
     @Override 
     public AuthenticationManager authenticationManagerBean() 
       throws Exception { 
      return super.authenticationManagerBean(); 
     } 

    } 

答えて

1

です。

@Autowired 
private MyAuthenticationProvider authenticationProvider; 

protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.authenticationProvider(authenticationProvider); 
} 

単に各ログインの試行のためにあなたのUserRepositoryを要求する独自のMyAuthenticationProviderを実装します。あるいは、単純に基本的なjdbcを使用する方法もあります:

protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.jdbcAuthentication().dataSource(dataSource) 
    .usersByUsernameQuery(
    "select username,password, enabled from users where username=?") 
    .authoritiesByUsernameQuery(
    "select username, role from user_roles where username=?"); 
} 

...もちろん、独自のクエリを設定する必要があります。

+0

私は単純化のために最初の解決策を使用しました:)ありがとうございました –

+0

これは、「UserRepository」という1つの場所で全体の「ユーザーの検索」ロジックを維持するという利点があるためです。 JDBCソリューションはそれを複製する傾向があり、何かが変更された場合、維持するのが難しくなります。 –

+0

こんにちはjdbcソリューションは、新しいロールを動的に更新しますか? –

関連する問題