2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Securityよく使用するアノテーション&メソッド

Last updated at Posted at 2024-08-01

Spring Securityでよく使用するアノテーション

  1. @EnableWebSecurity
    Spring SecurityのWebセキュリティサポートを有効にする。
    通常、セキュリティ設定クラスに付与する。

  2. @Secured
    メソッドレベルのセキュリティ制御を行うためのアノテーション。
    指定されたロールを持つユーザーのみがメソッドにアクセスできる。

  3. @PreAuthorize
    メソッドが呼び出される前にアクセス権をチェックする。
    SpEL(Spring Expression Language)を使用して条件を記述する。

  4. @PostAuthorize
    メソッドの実行後にアクセス権をチェックする。
    SpELを使用して条件を記述する。

  5. @RolesAllowed
    Java EEの@RolesAllowedアノテーションをSpring Securityでサポートする。
    指定されたロールを持つユーザーのみがメソッドにアクセスできる。

  6. @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();

【参考】

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?