OAuth2.0 SpringBoot の構築

Prev Next

Classic/VPC環境で利用できます。

プロジェクト設定

Springの色んな OAuth Authorization Server実装プロジェクトの中で Spring Authorization Serverを基準に説明します。OAuth連携のために必要な Authorization Code Grant、Refresh Tokenが既に実装されているので、サービスに合わせて少しカスタマイズするとすぐに使用できます。

参考

Spring/Spring Bootプロジェクトの設定や開発方法は、Spring Authorization Server Referenceをご参照ください。

実装例

実装サンプルコードを照会します。

基本設定

基本設定のサンプルコードは、次の通りです。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.config.Settings;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServiceConfigurers;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServer;
import org.springframework.security.web.SecurityFilterChain;
 
@Configuration
public class AuthorizationServerConfig {
 
    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/.well-known/jwks.json").permitAll()
                    .anyRequest().authenticated()
            )
            .formLogin(withDefaults());
        return http.build();
    }
 
    @Bean
    public InMemoryUserDetailsManager userDetailsManager() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }
 
    @Bean
    public InMemoryRegisteredClientRepository registeredClientRepository() {
        return new InMemoryRegisteredClientRepository(ClientRegistration.withRegistrationId("custom")
                .clientId("custom-client")
                .clientSecret("custom-secret")
                .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .redirectUri("http://localhost:8080/login/oauth2/code/custom")
                .scope("openid")
                .clientName("Custom Client")
                .build()
        );
    }
 
    @Bean
    public OAuth2AuthorizationService authorizationService() {
        return new OAuth2AuthorizationService(new OAuth2AuthorizationServiceConfigurers()
                .authorizationProviderSettings(ProviderSettings.builder().issuer("https://idp.example.com").build())
                .settings(Settings.builder()
                        .issuer("https://idp.example.com")
                        .clientId("custom-client")
                        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                        .redirectUri("http://localhost:8080/login/oauth2/code/custom")
                        .clientName("Custom Client")
                        .build())
        );
    }
 
}
  1. サンプルコードでは必要な依存関係や設定を含めた Spring Authorization Serverの構成を示します。これには、ユーザー認証、クライアント登録、OIDC設定が含まれます。
  2. OIDCエンドポイント: OIDC(OpenID Connect)構成に従って認証と OIDCエンドポイントを設定します。
  3. UserDetails Manager: ユーザーの詳細を管理するために InMemoryUserDetailsManagerを設定します。
  4. Registered Client Repository: クライアントアプリケーションを登録して設定します。
  5. OAuth2 Authorization Service: OAuth 2.0認可サービスを設定します。
    • 上記例は Spring Authorization Serverを使って OAuth 2.0認証サーバを実装するための基本設定とコードです。実環境に合わせて設定を変更する必要があり、ユーザー、クライアント、OIDCの設定を適切に設定する必要があります。Spring Authorization Serverの文書を詳しく確認した後、必要な設定を追加で設定する必要があります。
    • InMemoryに設定されている部分を各サービスで使用している Persistent DBに変更する必要があります。

Endpoint設定

Endpoint設定のサンプルコードは、次の通りです。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/oauth/authorize").permitAll()
                .antMatchers("/prism/v1/service/oauth2/token").permitAll()
                .antMatchers("/prism/v1/service/**").authenticated()
                .and()
            .csrf().disable();
    }
}
  • OAuth2ログインとトークン発行のためのパスを設定します。
    • OAuth2ログイン: デフォルトは /oauth/authorizeで、サービスで希望するパスに設定できます。
    • トークンの発行と更新: /prism/v1/service/oauth2/tokenに設定する必要があります。
  • permitAll(): このルールは、当該 URLまたはパターンに対するすべてのリクエストを許可します。OAuth2ログインおよびトークン発行のためのパスを設定します。
  • authenticated(): このルールは、当該 URLまたはパターンに対するアクセスが認証されたユーザーにのみ許可します。保護すべきリソースに使用されます。ログイン関連の URLを除くサービス APIパターンを設定します。