1. 概要

この記事は、 Spring Security のJava構成の概要です。これにより、ユーザーはXMLを使用せずにSpringSecurityを簡単に構成できます。

Java構成はSpring3.1 でSpringフレームワークに追加され、 Spring 3.2でSpringSecurityに拡張され、@Configurationという注釈の付いたクラスで定義されています。

2. Mavenのセットアップ

MavenプロジェクトでSpringSecurityを使用するには、最初にプロジェクトpom.xmlspring-security-core依存関係を設定する必要があります。

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.3.3.RELEASE</version>
</dependency>

最新バージョンはいつでもここで見つけることができます。

3. Java構成によるWebセキュリティ

SpringセキュリティJava構成の基本的な例から始めましょう。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth.inMemoryAuthentication().withUser("user")
          .password(passwordEncoder().encode("password")).roles("USER");
    }
}

お気づきかもしれませんが、この構成では基本的なメモリ内認証構成が設定されます。 さらに、Spring 5以降、 PasswordEncoderBeanが必要です。

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

4. HTTPセキュリティ

SpringでHTTPセキュリティを有効にするには、 WebSecurityConfigurerAdapter を拡張して、 configure(HttpSecurity http)メソッドでデフォルト構成を提供する必要があります。

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().httpBasic();
}

上記のデフォルト構成では、アプリケーションへのすべての要求がフォームベースのログインまたはHTTP基本認証で認証されていることを確認します。

また、次のXML構成とまったく同じです。

<http>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <form-login />
    <http-basic />
</http>

5. フォームログイン

興味深いことに、Spring Securityは、有効になっている機能に基づいて、送信されたログインを処理するURLの標準値を使用して、ログインページを自動的に生成します。

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().formLogin()
      .loginPage("/login").permitAll();
}

ここで、自動生成されたログインページは、すばやく起動して実行するのに便利です。

6. 役割による承認

次に、ロールを使用して各URLにいくつかの簡単な承認を構成しましょう。

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/", "/home").access("hasRole('USER')")
      .antMatchers("/admin/**").hasRole("ADMIN")
      .and()
      // some more method calls
      .formLogin();
}

タイプセーフAPI– hasRole –と、accessを介した式ベースのAPIの両方を使用していることに注目してください。

7. ログアウト

Spring Securityの他の多くの側面と同様に、ログアウトにはフレームワークによって提供されるいくつかの優れたデフォルトがあります。

デフォルトでは、ログアウト要求はセッションを無効にし、認証キャッシュをクリアし、 SecurityContextHolder をクリアして、ログインページにリダイレクトします。

簡単なログアウト設定は次のとおりです。

protected void configure(HttpSecurity http) throws Exception {
    http.logout();
}

ただし、使用可能なハンドラーをより細かく制御したい場合は、より完全な実装は次のようになります。

protected void configure(HttpSecurity http) throws Exception {
    http.logout().logoutUrl("/my/logout")
      .logoutSuccessUrl("/my/index")
      .logoutSuccessHandler(logoutSuccessHandler) 
      .invalidateHttpSession(true)
      .addLogoutHandler(logoutHandler)
      .deleteCookies(cookieNamesToClear)
      .and()
      // some other method calls
}

8. 認証

SpringSecurityで認証を許可する別の方法を見てみましょう。

8.1. インメモリ認証

単純なメモリ内構成から始めます。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
      .and()
      .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
}

8.2. JDBC認証

これをJDBCに移行するには、アプリケーション内でデータソースを定義し、それを直接使用するだけです。

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
      .withDefaultSchema()
      .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
      .and()
      .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
}

もちろん、上記の両方の例では、セクション3で概説されているように、PasswordEncoderBeanも定義する必要があります。

9. 結論

このクイックチュートリアルでは、Spring SecurityのJava構成の基本を確認し、最も単純な構成シナリオを示すコードサンプルに焦点を当てました。