Spring Security 処理フロー
Spring Securityについて記述する。
- PreAuthenticationProcessing
- UserDetailService
- PreAuthorize
- PostAuthorize
Spring Security
Spring Securityによる認証認可について記述する。
複数のシステムからの認証認可を行いたいケースでの利用や厳密なアクセス制御を行いたい1システムでの利用が可能。
なので、認証サーバーだけの役割としてもSpring Securityを利用が可能だと思われる。
AbstractPreAuthenticatedProcessingFilter
AbstractPreAuthenticatedProcessingFilterは、HTTPリクエストに対してgetUserPrincipalメソッドを呼び出して処理を行う。
ここでは、ユーザのクレデンシャル情報を取得してセットするだけであり、認証処理はまだ実行しない。
どのような処理か?
setAuthenticationFailureHandlerとsetAuthenticationSuccessHandlerで処理されて、セットされたユーザ情報を抽出する。または、独自実装等で、リクエストに含んでいるトークンさらに認証サーバへの問い合わせをするといったことの実装も可能。
また、処理したユーザーの認証情報が空の場合は、AuthenticationManagerに渡されるようになっている。
抽象メソッドは以下。1
2protected abstract Object getPreAuthenticatedPrincipal(HttpServletRequest request);
protected abstract Object getPreAuthenticatedCredentials(HttpServletRequest request);
AuthenticationUserDetailsService
PreAuthenticatedAuthenticationProviderは、認証処理をAuthenticationUserDetailsServiceに移譲しているクラス。
AuthenticationUserDetailsServiceは、UserDetailsServiceに似ていて認証のオブジェクトとユーザ名を受け取る処理を行う。
PreAuthenticatedAuthenticationTokenを実装するクラスである。
認証に失敗した場合、UsernameNotFoundExceptionクラスをthrowする。
1 | public interface AuthenticationUserDetailsService { |
ユーザのクレデンシャル情報は、PreAuthenticatedAuthenticationTokenで処理されて、独自で実装するAuthenticationUserDetailsServiceの実装クラスに渡される。
独自実装で、クレデンシャル情報を取得して認証を実行する必要がある。
1 | public class CustomService implements AuthenticationUserDetailsService { |
SecurityConfig
Spring SecurityのConfigクラスはWebSecurityConfigurerAdapterを継承して実装する必要がある。
Configクラスは、どのエンドポイントでSpring Securityを有効にするのかを定義することができる。
If we want to access allow any endpoint, we can use HttpSecurity.
なので、エンドポイントレベルでSecurityを適用させたい場合は、このConfigクラスの実装が必要となる。
1 |
|
PreAuthorize
@PreAuthorizeは、Springで実装したメソッドの処理の前に認証認可を実行することができるアノテーション。
Adminの権限やその他の権限を、メソッドレベルで認可したい場合には有効なアノテーションである。
1 | "hasAuthority('ADMIN')") ( |
PostAuthorize
@PostAuthorize Springで実装したメソッドの処理の後に認証認可を実行することができるアノテーション。
そこまで使い道が思い浮かばないので、省略。
1 | "returnObject=='hoge'") ( |