Spring Security用のJava Configの紹介

Spring SecurityのJava Configの概要

1. 概要

この記事はan introduction to Java configuration for Spring Securityであり、ユーザーはXML.を使用せずにSpringSecurityを簡単に構成できます。

Java構成はSpring 3.1でSpringフレームワークに追加され、Spring 3.2でSpring Securityに拡張され、@Configurationという注釈が付けられたクラスで定義されています。

2. Mavenセットアップ

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


    org.springframework.security
    spring-security-core
    4.1.3.RELEASE

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

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

Spring SecurityJava構成の基本的な例から始めましょう。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

お気づきかもしれませんが、この構成は基本的なメモリ内認証構成をセットアップします。

4. HTTPセキュリティ

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

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

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

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


    
    
    

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. 認証

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

8.1. インメモリ認証

シンプルなメモリ内構成から始めます。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
  throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password("password").roles("USER")
      .and()
      .withUser("admin").password("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("password").roles("USER")
      .and()
      .withUser("admin").password("password").roles("USER", "ADMIN");
}

9. 結論

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