OAuth2.0 SpringBoot 구축
    • PDF

    OAuth2.0 SpringBoot 구축

    • PDF

    기사 요약

    Classic/VPC 환경에서 이용 가능합니다.

    프로젝트 설정

    Spring의 여러 OAuth Authorization Server 구현 프로젝트 중 Spring Authorization Server를 기준으로 설명합니다. PRISM OAuth 연동을 위해 필요한 Authorization Code Grant, Refresh Token이 이미 구현되어 있으므로 서비스에 맞는 약간의 커스터마이징을 거치면 바로 사용이 가능합니다.

    구현 예시

    구현 예시 구문을 소개합니다.

    기본 설정

    기본 설정 예시 구문은 다음과 같습니다.

    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 패턴을 설정합니다.

    이 문서가 도움이 되었습니까?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.