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 配下に配置する。