Spring Securityでよく使用するアノテーション
-
@EnableWebSecurity
Spring SecurityのWebセキュリティサポートを有効にする。
通常、セキュリティ設定クラスに付与する。 -
@Secured
メソッドレベルのセキュリティ制御を行うためのアノテーション。
指定されたロールを持つユーザーのみがメソッドにアクセスできる。 -
@PreAuthorize
メソッドが呼び出される前にアクセス権をチェックする。
SpEL(Spring Expression Language)を使用して条件を記述する。 -
@PostAuthorize
メソッドの実行後にアクセス権をチェックする。
SpELを使用して条件を記述する。 -
@RolesAllowed
Java EEの@RolesAllowedアノテーションをSpring Securityでサポートする。
指定されたロールを持つユーザーのみがメソッドにアクセスできる。 -
@AuthenticationPrincipal
コントローラメソッドの引数に認証されたユーザー情報を直接注入する。
Spring Securityでよく使用するメソッド
1. HttpSecurity
セキュリティ設定をカスタマイズするために使用されるメインクラス。
各種設定メソッドをチェーンして使用する。
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
2. AuthenticationManagerBuilder
認証の設定を行うために使用されるクラス。
ユーザー情報の設定やパスワードエンコーダーの設定などを行う。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
}
3. UserDetailsService
カスタムユーザーデータをロードするためのインターフェース。
loadUserByUsernameメソッドを実装して、ユーザー情報を取得する。
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// ユーザー情報の取得とUserDetailsオブジェクトの作成
}
}
4. PasswordEncoder
パスワードをエンコードするためのインターフェース。
通常、BCryptPasswordEncoderなどの実装クラスを使用する。
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
5. SecurityContextHolder
認証情報を取得するためのクラス。
現在の認証されたユーザー情報にアクセスできる。
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
【参考】