Spring Securityデータベースによる認証ユーザ登録

2338 ワード

Spring Securityはデフォルトの登録ページを提供してくれます.Authentication ManagerBuiderをパラメータとするconfigure方法を書き換えることによって、メモリ、関係データベース、LDAPなどの各種データストアに基づいてユーザーを認証することができます.
問題
データベーステーブルを使って認証する時、書き換えたconfigurは以下の通りです.
	@Autowired
    DataSource datasource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
        .usersByUsernameQuery(
                "SELECT username, password FROM users WHERE username=?");
   }
Spring Securityには三つのデフォルトのクエリ文がありますので、データベーステーブルに対して一定の要求があります.権限、グループの定義が必要ですが、自分のusersテーブルは簡単で、権限、グループの属性を定義していません.だから、基本的なクエリーの文言を書き直しました.どのように試しても認証できませんでした.ログインページを書き直したので、問題がどこにあるかは分かりませんでした.デフォルトのログインページを復元した後、エラー情報によって発見されました.デフォルトのユーザーの問い合わせ文を書き直しましたが、誤ってauthorityという表はありません.だから、デフォルトのデータベース認証を使うなら、私達のデータベーステーブルのパターンはSpring Securityと一致します.ここにはユーザーテーブルしかありません.パーミッションがないとエラーが発生します.私たちはSpring Securityのデフォルト登録を使う権限表が必要ですか?答えはもちろんです.
ユーザーサービスの設定
次に、ユーザーサービスを設定し、UserDetails Serviceインターフェースを実現し、そのloadUserByUsername方法を書き換える必要があります.
public class SpitterUserService implements UserDetailsService {

    private final SpitterRepository spitterRepository;

    @Inject
    public SpitterUserService(SpitterRepository spitterRepository){
        this.spitterRepository=spitterRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Spitter spitter=spitterRepository.findUserByName(username);
        if(spitter!=null){
            List authorities=new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_SPITTER"));

            return new User(spitter.getUsername(),
                    spitter.getPassword(),
                    authorities);
        }

        throw new UsernameNotFoundException("" +
                "User "+ username+ "not found");

    }
}
configureを書き換えてセキュリティ設定にします.
@Autowired
    SpitterRepository spitterRepository;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(new SpitterUserService(spitterRepository));
    }
これにより、カスタマイズしたユーザの認証ができます.