Spring Security –登録後の自動ログインユーザー
1. 概要
このクイックチュートリアルでは、Spring Securityの実装で、登録プロセスの直後にユーザーを自動認証する方法について説明します。
簡単に言うと、ユーザーが登録を完了すると、通常はログインページにリダイレクトされ、ユーザー名とパスワードを再入力する必要があります。
代わりにユーザーを自動認証することで、これを回避する方法を見てみましょう。
始める前に、このサイトのregistration seriesの範囲内で作業していることに注意してください。
2. HttpServletRequestの使用
プログラムで認証を強制する非常に簡単な方法は、HttpServletRequest login()メソッドを利用することです。
public void authWithHttpServletRequest(HttpServletRequest request, String username, String password) {
try {
request.login(username, password);
} catch (ServletException e) {
LOGGER.error("Error while login ", e);
}
}
これで、内部的には、HttpServletRequest.login() APIはAuthenticationManagerを使用して認証を実行します。
このレベルで発生する可能性のあるServletExceptionを理解し、対処することも重要です。
3. AuthenticationManagerの使用
次に、UsernamePasswordAuthenticationTokenを直接作成して、標準のAuthenticationManagerを手動で実行することもできます。
public void authWithAuthManager(HttpServletRequest request, String username, String password) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
authToken.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
トークンリクエストを作成し、それを標準の認証フローに渡してから、現在のセキュリティコンテキストで結果を明示的に設定していることに注目してください。
4. 複雑な登録
より複雑なシナリオでは、登録プロセスに複数の段階があります。たとえば、ユーザーがシステムにログインできるようになるまでの確認ステップなどです。
このような場合、もちろん、ユーザーを自動認証できる場所を正確に理解することが重要です。 その時点では、新しく作成されたアカウントはまだ無効になっているため、登録直後にそれを行うことはできません。
簡単に言えば–we have to perform the automatic authentication after they confirm their account。
また、その時点で、実際の生の資格情報にアクセスできなくなっていることに注意してください。 ユーザーのエンコードされたパスワードにのみアクセスできます。これをここで使用します。
public void authWithoutPassword(User user){
List privileges = user.getRoles().stream()
.map(role -> role.getPrivileges())
.flatMap(list -> list.stream())
.distinct().collect(Collectors.toList());
List authorities = privileges.stream()
.map(p -> new SimpleGrantedAuthority(p.getName()))
.collect(Collectors.toList());
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
ここでは、AuthenticationProvider.で通常行われるように、認証機関を適切に設定していることに注意してください。
5. 結論
登録プロセス後にユーザーを自動認証するさまざまな方法について説明しました。
いつものように、完全なソースコードはover on GitHubで利用できます。