📝

Spring Authorization Server お勉強メモ #2

に公開

はじめに

Spring Authorization Server を調べた際のメモです

  • OIDC や OAuth の仕様を体系的にまとめたものではありません
  • Spring Authorization Server のコードをざっくり読みながら書き出しています
  • 自分用メモ です
  • Spring Authorization Server お勉強メモ #1 からの続きです

このドキュメントに書いてあること

  • #1 の続きで、今度は demo-authorizationserver を対象に、default-authorizationserver との違い(カスタムログイン・同意画面、Java 設定、H2 による DB 利用)を説明しています
  • DefaultSecurityConfig(formLogin / oauth2Login でローカル+Google・GitHub ログイン、SessionRegistry・HttpSessionEventPublisher)と AuthorizationServerConfig(authorizationServer・consentPage・oidc、認可エンドポイント対象の securityMatcher)の役割と、JdbcRegisteredClientRepository / JdbcOAuth2AuthorizationService / JdbcOAuth2AuthorizationConsentService など DB 連携の Bean を整理しています
  • メタデータエンドポイント、カスタムログイン/同意画面の流れ、/oauth2/authorize での未認証時の /login リダイレクトと認証後の再実行、トークンエンドポイントの処理までをメモしています

今回の検証モジュール

本メモでは demo-authorizationserver を検証対象とします。

モジュール名 説明
oauth2-authorization-server ライブラリモジュール
spring-security-oauth2-authorization-server 本体
demo-authorizationserver Authorization Server アプリケーション
oauth2-authorization-server を利用
demo-client Client アプリケーション
spring-boot-starter-oauth2-client を利用
#1 で検証したので今回は対象外
messages-resource Resource Server アプリケーション
spring-boot-starter-oauth2-resource-server を利用
#1 で検証したので今回は対象外
┌─────────────────────────────────────────────────────────┐
│                 Authorization Server                    │
│                                                         │
│  Application Name : demo-authorizationserver            │
│  Base URL         : http://localhost:9000               │
│  Library          : oauth2-authorization-server         │
│                                                         │
│  Responsibilities:                                      │
│  - User Authentication                                  │
│  - User Consent & Authorization                         │
│  - Token Issuance (ID Token / Access Token)             │
│  - OpenID Provider (OIDC)                               │
│                                                         │
└───────────────────────▲───────────────────────▲─────────┘
                        │                       │
        Authorization Request                   │Token Request
                        │                       │
                        │                       │
┌───────────────────────┴───────────────────────┴─────────┐
│                         Client                          │
│                                                         │
│  Application Name : demo-client                         │
│  Base URL         : http://localhost:8080               │
│  Library          : spring-boot-starter-oauth2-client   │
│                                                         │
│  Responsibilities:                                      │
│  - Entry point for the user's browser                   │
│  - Initiates Authorization Code Flow                    │
│  - Receives Authorization Code                          │
│  - Exchanges code for Access Token and ID Token         │
│                                                         │
└───────────────────────▲───────────────────────┬─────────┘
                        │                       │
            API Request (Bearer Access Token)   │
                        │                       │
┌───────────────────────┴───────────────────────▼─────────┐
│                     Resource Server                     │
│                                                         │
│  Application Name : messages-resource                   │
│  Base URL         : http://localhost:8090               │
│  Library          : spring-boot-starter-oauth2-resource-server
│                                                         │
│                                                         │
│  Responsibilities:                                      │
│  - Provides protected REST APIs                         │
│  - Validates Access Tokens (JWT / Introspection)        │
│  - Authorizes requests based on scopes / authorities    │
│                                                         │
└─────────────────────────────────────────────────────────┘

demo-authorizationserver アプリケーション

Spring Authorization Server を使った Authorization Server アプリケーション
#1 で検証した default-authorizationserver との違いは以下のとおりです。

  • application.yml の設定はあまりない代わりに DefaultSecurityConfig.java, AuthorizationServerConfig.java でアプリケーション設定をしている
  • カスタムログイン画面、カスタム同意画面を実装している
  • DB を使っている(H2 インメモリ)
  • Spring Security: 7.0.0-M2 を使用している

アプリケーション設定: application.yml

server:
  # このアプリケーションの起動ポート
  # port 9443 となっているがこれはHTTPSでの起動ポート
  # TomcatServerConfig で HTTP での起動ポート 9000 が設定されている
  port: 9443
  ssl:
    bundle: demo-authorizationserver
    client-auth: want

spring:
  ssl:
    bundle:
      jks:
        demo-authorizationserver:
          key:
            alias: demo-authorizationserver-sample
            password: password
          keystore:
            location: classpath:keystore.p12
            password: password
            type: PKCS12
          truststore:
            location: classpath:keystore.p12
            password: password
            type: PKCS12
  security:
    oauth2:
      client:
        registration:
          # google でログインするときのIDP設定
          google-idp:
            provider: google
            client-id: ${GOOGLE_CLIENT_ID:google-client-id}
            client-secret: ${GOOGLE_CLIENT_SECRET:google-client-secret}
            scope: openid, https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email
            client-name: Sign in with Google

          # GitHub でログインするときのIDP設定
          github-idp:
            provider: github
            client-id: ${GITHUB_CLIENT_ID:github-client-id}
            client-secret: ${GITHUB_CLIENT_SECRET:github-client-secret}
            scope: user:email, read:user
            client-name: Sign in with GitHub
        provider:
          google:
            user-name-attribute: email
          github:
            user-name-attribute: login

logging:
  level:
    root: INFO
    org.springframework.web: INFO
    org.springframework.security: INFO
    org.springframework.security.oauth2: INFO

アプリケーション設定: DefaultSecurityConfig

@Bean SecurityFilterChain

Spring Security標準の HttpSecurity 設定

HttpSecurity 設定 Configurer
authorizeHttpRequests URL の権限設定 AuthorizeHttpRequestsConfigurer
formLogin カスタムログイン画面の設定 FormLoginConfigurer
oauth2Login OAuth ログイン機能の設定 OAuth2LoginConfigurer

authorizeHttpRequests

  • /assets/** /login エンドポイントへのアクセスは 認証不要
  • それ以外の全てのエンドポイントへのアクセスは 認証が必要

formLogin

フォーム認証によるログイン機能の設定。ここでは FormLoginConfigurer による設定と、loginPage によるカスタム設定を行っている。

  • FormLoginConfigurer
    • UsernamePasswordAuthenticationFilter フィルタが有効になり、 /login に対する POST リクエストを処理するようになる
  • loginPage
    • ログインページのカスタム指定
    • この設定により Spring Security のデフォルトログインページが無効になり、ここで指定した URL がログイン画面になる
      • FormLoginConfigurer#initDefaultLoginFilter

oauth2Login

OAuth2 クライアント設定

  • この認可サーバー自体が OAuth2 クライアント(Relying Party)として振る舞う設定

  • カスタムログイン画面で外部 ID プロバイダー(Google・GitHub)によるユーザー認証を行うため、クライアントとしての設定も行っている

    • ID プロバイダーの設定は、application.yml の spring.security.oauth2.client.registration(google-idp、github-idp)で定義されている
  • ここでは OAuth2LoginConfigurer による設定, loginPage, successHandler によるカスタム設定を行っている

  • OAuth2LoginConfigurer

    • #1 の demo-client でも使っている
    • OAuth2LoginAuthenticationFilter が有効になり、 /login/oauth2/code/* を処理するようになる
    • OAuth2AuthorizationRequestRedirectFilter が有効になり、 /oauth2/authorization/* を処理するようになる
  • loginPage

    • OAuthクライアントとしてのログインページが /login になる
  • successHandler

    • 認証が成功したときのハンドラ(FederatedIdentityAuthenticationSuccessHandler)を設定している

/login について

formLogin と oauth2Login の両方で .loginPage("/login") 設定している

  • カスタムログイン画面から
    • ローカルユーザー(form login)でログインもできるし
    • Google / GitHub(oauth2 login)もできる
  • login.html を見ると
    • /oauth2/authorization/google-idp
    • /oauth2/authorization/github-idp
    • と書いてあり、この形式は /oauth2/authorization/{registrationId} の形式になっている(Spring Securityログイン開始用の標準エンドポイント形式)
    • registrationId の設定は application.yml に書いてある

@Bean HttpSessionEventPublisher

セッション状況を Spring Security に知らせる通知役

  • この Bean を作成すると、セッションの生成・セッション ID 変更・破棄のときにイベントを発行するようになる
    • JSESSIONID 生成時: HttpSessionCreatedEvent
    • JSESSIONID 変更時(ログインしたとき): HttpSessionIdChangedEvent
    • JSESSIONID 破棄時(ログアウトしたとき): HttpSessionDestroyedEvent
  • Spring Session を使う場合はこの Bean は不要になる
  • セッション管理する場合は必須だが、この Bean は自動では生成されない仕様のようである

@Bean SessionRegistryImpl

誰(Principal)がどの sessionId でログインしているかを管理する

  • JSESSIONID 生成時・変更時・破棄時にこのデータが更新される
    • ログイン成功時
      • spring-authorization-server の OAuth2AuthorizationServerConfigurer#init から sessionRegistry.registerNewSession
    • ログオフ時、JSESSIONIDが変わった時
      • sessionRegistry#onApplicationEvent が HttpSessionDestroyedEvent を拾っている

HttpSessionEventPublisher と SessionRegistryImpl は両方必要

認可サーバー設定: AuthorizationServerConfig

こちらもアプリケーション設定だが OAuth2 / OIDC プロトコルに関連する設定をしている
DefaultSecurityConfig とは役割が異なるため、ファイルを分けているようだ

@Bean SecurityFilterChain

OAuth2 / OIDC プロトコルに関連するエンドポイントに関する設定

HttpSecurity 設定 AbstractHttpConfigurer
securityMatcher SecurityFilterChain の対象範囲を設定する -
authorizationServer Authorization Server設定 OAuth2AuthorizationServerConfigurer
authorizeHttpRequests SecurityFilterChain に入ってきたリクエストの認可設定 AuthorizeHttpRequestsConfigurer
exceptionHandling SecurityFilterChain に入ってきたリクエストの例外処理設定 ExceptionHandlingConfigurer

securityMatcher

OAuth2AuthorizationServerConfigurer#getEndpointsMatcher を使って取得したエンドポイント(/oauth2/authorize、/oauth2/token など 全ての OAuth2 エンドポイント)を対象にしている
以降の設定は全てここで対象になったものにのみ適用される

authorizationServer

ここでは OAuth2AuthorizationServerConfigurer による設定と、以下のカスタム設定を行っている

  • deviceAuthorizationEndpoint: Device Code Flow 用の設定(今回の検証の対象外)

  • deviceVerificationEndpoint: Device Code Flow 用の設定(今回の検証の対象外)

  • clientAuthentication: Device Code Flow 用の設定(今回の検証の対象外)

  • authorizationEndpoint: 後述

  • oidc: 後述

  • OAuth2AuthorizationServerConfigurer

    • 以下のフィルターが有効になり、認可サーバーとしての機能が有効になる
      • OAuth2AuthorizationServerMetadataEndpointFilter
        • パス: /.well-known/oauth-authorization-server
      • OAuth2AuthorizationEndpointFilter
        • パス: /oauth2/authorize
      • OAuth2TokenEndpointFilter
        • パス: /oauth2/token
      • OAuth2TokenIntrospectionEndpointFilter
        • パス: /oauth2/introspect
      • OAuth2TokenRevocationEndpointFilter
        • パス: /oauth2/revoke
      • NimbusJwkSetEndpointFilter
        • パス: /oauth2/jwks
  • authorizationEndpoint: 認可エンドポイント設定

    • consentPage に /oauth2/consent を設定している
      • 同意画面のパス設定
      • Authorization Code Flow のときに requireAuthorizationConsent が true であれば、ユーザーに同意をとるためにこのパスにリダイレクトされるようになる
      • このアプリでは同意画面を自作しており、 AuthorizationConsentController に実装している
  • oidc: OpenID Connect 設定

    • デフォルトの設定を有効にしている(OidcConfigurer)
    • これでOIDCのエンドポイントが有効になる
      • /.well-known/openid-configuration
      • /connect/logout
      • /userinfo
    • OAuth2AuthorizationServerConfigurer では自動で設定されないため、 Customizer.withDefaults() でも指定する必要がある
      • 自動では設定されない → OAuth2AuthorizationServerConfigurer#createConfigurers に OidcConfigurer が含まれていない

.with(authorizationServerConfigurer, (authorizationServer) -> について

  • 既存の SecurityConfigurer を HttpSecurity に適用し、その configurer を Customizer でカスタマイズする書き方
    public <C extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>>
    HttpSecurity with(
        C configurer, // 第1引数: SecurityConfigurer
        Customizer<C> customizer // 第2引数: Customizer
    )
    
  • Spring Security 6.0 では authorizationServerConfigurer を設定するメソッドが HttpSecurity に存在しないため、この書き方になる
    • このプロジェクトは spring-security.version=7.0.0-M2 (M2→M3→RC1→RC2→RC3→7.0.0→7.0.1→7.0.2)
  • Spring Security 7.0 であれば HttpSecurity に oauth2AuthorizationServer というメソッドが追加されている

https://github.com/spring-projects/spring-security/blob/9d08114c5895de3a44eb3bace74f0113ea258c54/config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java#L1522-L1536

  • そのため、with を使わずに書ける(こちらの書き方の方が簡潔)
    http
      .securityMatcher(authorizationServerEndpointsMatcher)
      .oauth2AuthorizationServer(authorizationServer -> {
          authorizationServer.oidc(Customizer.withDefaults());
          // ここでカスタマイズ
      });
    

authorizeHttpRequests

securityMatcherで指定した全てのエンドポイントは認証が必要

authorize.anyRequest().authenticated()

exceptionHandling

例外ハンドリング設定

  • 認証が必要なサイトでエラーが起きた場合(主に未認証だった場合)
  • かつ、リクエストの MediaType が HTML だった場合
  • /loginにリダイレクトする
    (ライブラリ側で自動対応していそうだが、現状では行われていない)

@Bean JdbcRegisteredClientRepository

クライアント定義を JdbcRegisteredClientRepository で DB に保存している
Table: oauth2_registered_client (oauth2-registered-client-schema.sql)

カラム名 データ型 NULL 初期値
id varchar(100) No -
client_id varchar(100) No -
client_id_issued_at timestamp No CURRENT_TIMESTAMP
client_secret varchar(200) Yes NULL
client_secret_expires_at timestamp Yes NULL
client_name varchar(200) No -
client_authentication_methods varchar(1000) No -
authorization_grant_types varchar(1000) No -
redirect_uris varchar(1000) Yes NULL
post_logout_redirect_uris varchar(1000) Yes NULL
scopes varchar(1000) No -
client_settings varchar(2000) No -
token_settings varchar(2000) No -

このアプリケーションでは以下の client_id を作成している

  • messaging-client
  • device-messaging-client
  • token-client
  • mtls-demo-client

@Bean JdbcOAuth2AuthorizationService

認証・認可情報を DB の oauth2_authorization テーブルに保存する Service クラスを生成している

Table: oauth2_authorization (oauth2-authorization-schema.sql)

カラム名 データ型 制約 / デフォルト値
id varchar(100) PRIMARY KEY, NOT NULL
registered_client_id varchar(100) NOT NULL
principal_name varchar(200) NOT NULL
authorization_grant_type varchar(100) NOT NULL
authorized_scopes varchar(1000) DEFAULT NULL
attributes blob DEFAULT NULL
state varchar(500) DEFAULT NULL
authorization_code_value blob DEFAULT NULL
authorization_code_issued_at timestamp DEFAULT NULL
authorization_code_expires_at timestamp DEFAULT NULL
authorization_code_metadata blob DEFAULT NULL
access_token_value blob DEFAULT NULL
access_token_issued_at timestamp DEFAULT NULL
access_token_expires_at timestamp DEFAULT NULL
access_token_metadata blob DEFAULT NULL
access_token_type varchar(100) DEFAULT NULL
access_token_scopes varchar(1000) DEFAULT NULL
oidc_id_token_value blob DEFAULT NULL
oidc_id_token_issued_at timestamp DEFAULT NULL
oidc_id_token_expires_at timestamp DEFAULT NULL
oidc_id_token_metadata blob DEFAULT NULL
refresh_token_value blob DEFAULT NULL
refresh_token_issued_at timestamp DEFAULT NULL
refresh_token_expires_at timestamp DEFAULT NULL
refresh_token_metadata blob DEFAULT NULL
user_code_value blob DEFAULT NULL
user_code_issued_at timestamp DEFAULT NULL
user_code_expires_at timestamp DEFAULT NULL
user_code_metadata blob DEFAULT NULL
device_code_value blob DEFAULT NULL
device_code_issued_at timestamp DEFAULT NULL
device_code_expires_at timestamp DEFAULT NULL
device_code_metadata blob DEFAULT NULL

@Bean JdbcOAuth2AuthorizationConsentService

同意情報を DB の oauth2_authorization_consent テーブルに保存する Service クラスを生成している

Table: oauth2_authorization_consent (oauth2-authorization-consent-schema.sql)

カラム名 データ型 制約 / デフォルト値
registered_client_id varchar(100) PRIMARY KEY, NOT NULL
principal_name varchar(200) PRIMARY KEY, NOT NULL
authorities varchar(1000) NOT NULL

@Bean idTokenCustomizer

Google / GitHub ログインなどフェデレーション時の ID トークン変換機能を提供する。今回の検証では対象外

@Bean JWKSource

JWT の署名に使用する鍵(JWK)を提供する Bean

  • Jwks 実装を見ると作成している鍵の実装がわかる
  • このサンプルでは起動時に毎回新しい鍵を生成しているため、再起動で変わってしまう。通常はファイルや DB から読み込む実装が想定される

@Bean JwtDecoder

JWT の署名を検証するための Bean

@Bean AuthorizationServerSettings

基本設定情報、以下のようなオブジェクトを生成する

AuthorizationServerSettings: AbstractSettings {
  settings = {
    settings.authorization-server.authorization-endpoint = /oauth2/authorize, 
    settings.authorization-server.token-endpoint = /oauth2/token, 
    settings.authorization-server.device-verification-endpoint = /oauth2/device_verification, 
    settings.authorization-server.oidc-user-info-endpoint = /userinfo, 
    settings.authorization-server.pushed-authorization-request-endpoint = /oauth2/par, 
    settings.authorization-server.oidc-client-registration-endpoint = /connect/register, 
    settings.authorization-server.oidc-logout-endpoint = /connect/logout, 
    settings.authorization-server.multiple-issuers-allowed = false, 
    settings.authorization-server.device-authorization-endpoint = /oauth2/device_authorization, 
    settings.authorization-server.jwk-set-endpoint = /oauth2/jwks, 
    settings.authorization-server.token-revocation-endpoint = /oauth2/revoke, 
    settings.authorization-server.token-introspection-endpoint = /oauth2/introspect
  }
}

@Bean EmbeddedDatabase

DB生成処理

  • EmbeddedDatabaseBuilder を使って H2 Database を構築している
  • oauth2_registered_client、oauth2_authorization、oauth2_authorization_consent テーブルを作成している

メタデータエンドポイント

Request
GET http://localhost:9000/.well-known/oauth-authorization-server

Response
OAuth2AuthorizationServerMetadataEndpointFilter#doFilterInternal で処理し、以下のようなレスポンスを返す。

{
  "issuer": "http://localhost:9000",
  "authorization_endpoint": "http://localhost:9000/oauth2/authorize",
  "pushed_authorization_request_endpoint": "http://localhost:9000/oauth2/par",
  "device_authorization_endpoint": "http://localhost:9000/oauth2/device_authorization",
  "token_endpoint": "http://localhost:9000/oauth2/token",
  "token_endpoint_auth_methods_supported": [
    "client_secret_basic",
    "client_secret_post",
    "client_secret_jwt",
    "private_key_jwt",
    "tls_client_auth",
    "self_signed_tls_client_auth"
  ],
  "jwks_uri": "http://localhost:9000/oauth2/jwks",
  "response_types_supported": [
    "code"
  ],
  "grant_types_supported": [
    "authorization_code",
    "client_credentials",
    "refresh_token",
    "urn:ietf:params:oauth:grant-type:device_code",
    "urn:ietf:params:oauth:grant-type:token-exchange"
  ],
  "revocation_endpoint": "http://localhost:9000/oauth2/revoke",
  "revocation_endpoint_auth_methods_supported": [
    "client_secret_basic",
    "client_secret_post",
    "client_secret_jwt",
    "private_key_jwt",
    "tls_client_auth",
    "self_signed_tls_client_auth"
  ],
  "introspection_endpoint": "http://localhost:9000/oauth2/introspect",
  "introspection_endpoint_auth_methods_supported": [
    "client_secret_basic",
    "client_secret_post",
    "client_secret_jwt",
    "private_key_jwt",
    "tls_client_auth",
    "self_signed_tls_client_auth"
  ],
  "code_challenge_methods_supported": [
    "S256"
  ],
  "tls_client_certificate_bound_access_tokens": true,
  "dpop_signing_alg_values_supported": [
    "RS256",
    "RS384",
    "RS512",
    "PS256",
    "PS384",
    "PS512",
    "ES256",
    "ES384",
    "ES512"
  ]
}

カスタムログイン画面

  • Path
    • GET http://localhost:9000/login
  • Controller
    • LoginController
  • Resource
    • login.html

[Sign in] クリック時の処理

  • POST /login
    • Spring Securityの処理
      • DefaultSecurityConfig.java:52-55行目
      • UsernamePasswordAuthenticationFilter#attemptAuthentication
      • ユーザーは user1/password 固定
        • sample.config.DefaultSecurityConfig#users
    • ブラウザで直接 /login を指定して認証すると、認証後に / にリダイレクトされ、コントローラがないため 400 エラーになる点に注意
      • not found にならないのは authorizationServerSecurityFilterChain の設定による

認可エンドポイント

GET http://localhost:9000/oauth2/authorize

リクエスト例

GET
http://localhost:9000/oauth2/authorize?
  response_type = code
  &
  client_id = messaging-client
  &
  redirect_uri = http://localhost:8080/authorized
  &
  scope = openid
  • 有効な client_id は AuthorizationServerConfig#registeredClientRepository で定義されている
  • OAuth2AuthorizationEndpointFilter#doFilterInternal
    • if (!authenticationResult.isAuthenticated()) で未認証の場合は doFilter しており、この結果、/login にリダイレクトされる
      • /login にリダイレクトするが、このとき、元のリクエストを セッションに保存し、認証後に再度元のリクエストが実行される
        • セッションに保存 = ライブラリ内部のSpring Security標準のフィルタでやっている
          • ExceptionTranslationFilter#sendStartAuthentication
        • セッションからの取り出し = UsernamePasswordAuthenticationFilter の successfulAuthentication() でやっている
          • SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess
    • if (!authenticationResult.isAuthenticated()) で認証済みの場合
      • 認証結果(authenticationResult) が OAuth2AuthorizationConsentAuthenticationToken の場合、同意画面 http://localhost:9000/oauth2/consent にリダイレクトする
        • 同意画面に飛ばすかどうかの設定は requireAuthorizationConsent() で無効にできる
          • sample.config.AuthorizationServerConfig#registeredClientRepository
      • 同意後、またこのエンドポイントにリダイレクトされる

カスタム同意画面

  • Path
    • GET http://localhost:9000/oauth2/consent
  • Controller
    • AuthorizationConsentController
  • Resource
    • consent.html

トークンエンドポイント

POST http://localhost:9000/oauth2/token

  • OAuth2TokenEndpointFilter#doFilterInternal
  • onAuthenticationSuccess では成功レスポンスを返却
    • OAuth2AccessTokenResponseAuthenticationSuccessHandler
  • onAuthenticationFailure では失敗レスポンス
    • OAuth2ErrorAuthenticationFailureHandler

参考

Discussion