SpringBootを使用してSpringSecurityと連携して認証のインターセプトを実装する方法は何ですか?
Spring BootプロジェクトでSpring Securityを統合して認証インターセプトを実装するには、以下の手順に従うことができます。
- pom.xmlファイルにSpring Securityの依存関係を追加してください。
- <依存関係>
<グループID>org.springframework.boot</グループID>
<アーティファクトID>spring-boot-starter-security</アーティファクトID>
</依存関係> - Spring Security の設定クラスを作成します。このクラスは、WebSecurityConfigurerAdapter を継承しており、Spring Security を設定するために使用されます。
- import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {}
このコードは、Springのセキュリティ機能を有効化し、カスタムのセキュリティ設定を追加するためのクラスです。
- 設定認証と認可のルール:設定クラスでconfigure()メソッドをオーバーライドして、認証と認可のルールを設定します。
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(“/public/**”).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(“/login”)
.permitAll()
.and()
.logout()
.permitAll();
}
→
import org.springframework.security.config.annotation.web.builders.HttpSecurity;@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(“/public/**”).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(“/login”)
.permitAll()
.and()
.logout()
.permitAll();
} - ログインページを作成する:たとえばlogin.htmlというログインページを作成してください。
- configure()メソッドを再定義して、ユーザー情報とパスワードを暗号化する方法を設定する:設定クラス内に配置します。
- import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(“admin”)
.password(passwordEncoder().encode(“admin123”))
.roles(“ADMIN”);
}@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // Use BCryptPasswordEncoder for password encryption
} - 配置ファイルで静的リソースの無視を設定する:configure()メソッドをオーバーライドして、静的リソースへのアクセス制限を設定します。
- import org.springframework.security.config.annotation.web.builders.WebSecurity;@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(“/css/**”, “/js/**”, “/images/**”);
}このコードは、Spring SecurityのWebセキュリティ設定に対して、特定のURLパターンに対するアクセス権を無視するように指定しています。
- プロジェクトを実行してテストします:Spring Bootプロジェクトを起動し、認証が必要なリソースにアクセスします。システムはログインページにリダイレクトされ、ユーザー名とパスワードを入力して認証が完了します。
必要に応じて、カスタマイズや拡張を行うことができます。これにより、Spring BootとSpring Securityの認証インターセプトの設定が完了しました。