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セッション管理機能を追加する。
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
メソッドの引数により設定対象を変更できる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
contextConfigLocation
にspring-security.xml
、spring-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
配下に配置する。