ぺーぺーSEのブログ

備忘録・メモ用サイト。

Spring Security / Spring Session入門

Spring Securityは認証・認可の機能を持つSpringのライブラリ。
Spring Sessionを用いて Redis にセッションを格納する設定も試してみる。

ここでは、簡単なログイン画面でログインする機能を作成する。
以下の構成で記載する。

  • Java Configで設定する方法
    • Springの設定をJavaベースで設定する方法
  • XML Configで設定する方法
    • Springの設定をXMLベースで設定する方法
  • 共通作成物
    • Java Config、XML Configによらない共通の作成物

また、ここで紹介の作成物については以下参照のアプリケーションに対して、Thymeleaf画面・Spring Securityによる認証・Spring SessionによるRedisセッション管理機能を追加する。

blog.pepese.com

blog.pepese.com

Java Configで設定する方法

pom.xml

  • org.springframework.boot:spring-boot-starter-security を使用しているのがポイント

com.pepese.sample.config.WebSecurityConfig

  • org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter を継承し、 @EnableWebSecurity アノテーションを付与する
  • configure メソッドの引数により設定対象を変更できる
    • WebSecurity web : Spring Security Filter Chain (springSecurityFilterChain) に関する設定が可能
      • web.Xxx() で様々設定できる。詳細はここ
    • HttpSecurity http : XML Configの http タグと同じ設定が可能
      • http.Xxx() で様々設定できる。詳細はここ
  • configureGlobal メソッドで認証処理ロジックのサービスクラスをSpring Securityの認証マネージャに設定している

com.pepese.sample.config.SessionConfig

  • クラスに @EnableRedisHttpSession アノテーションを付与するとSpring Sessionの設定はほぼ完了
  • connectionFactory メソッドで Redis へセッションを格納する設定
  • ホスト名やポートは application.properties に設定する

XML Configで設定する方法

pom.xml

spring-mvc.xml

ThymeleafのView Resolverを設定。

spring-security.xml

  • <sec:http pattern="/resources/**" security="none" />
    • Spring Session処理対象外の設定
  • <sec:http>
    • 認証周りの設定
  • ユーザ認証処理ロジックのサービスクラス( UserDetailsServiceImpl )のBean定義
  • <sec:authentication-manager>
    • UserDetailsServiceImpl を認証マネージャに登録

spring-session.xml

  • RedisHttpSessionConfiguration のBean定義でSpring Sessionの設定
  • LettuceConnectionFactory のBean定義でRedis接続の設定

web.xml

  • contextConfigLocationspring-security.xmlspring-session.xml を追加。
  • Spring Securityの設定として springSecurityFilterChain という名前で org.springframework.web.filter.DelegatingFilterProxy をFilter定義しているのがポイント。
  • Spring Sessionの設定として springSessionRepositoryFilter という名前で org.springframework.web.filter.DelegatingFilterProxy をFilter定義しているのがポイント。
    • さらに Spring SecurityのFilter定義より上 に設定する必要がある

共通作成物

com.pepese.sample.model.User

  • 認証するユーザクラス
    • パスワードを固定にしているのはサンプルなので

com.pepese.sample.service.security.UserDetails

  • Spring Securityが提供するユーザ認証用のクラス( org.springframework.security.core.userdetails.User )を継承して作成
  • 自作のUserクラスを認証対象のクラスとして設定する

com.pepese.sample.service.security.UserDetailsServiceImpl

  • Spring Securityが提供するユーザ認証用サービスクラス( org.springframework.security.core.userdetails.UserDetailsService )を継承して作成
  • 本来なら認証対象のユーザデータをDBなどから取得して突合するが、サンプルということで new してる

application.properties

com.pepese.sample.controller.HelloController

  • @AuthenticationPrincipal でログイン済みのユーザ情報を取得できる
  • なお、 /logout のパス・ロジックは Spring Security にてもつ

index.html

Viewは、Java Configの場合は resources/templates 配下、XML Configの場合は WEB-INF/templates 配下に配置する。

login.html

error.html