Spring/Spring Security

[Spring Security] 7-1. OAuth2 Client: Core Interfaces and Classes

noahkim_ 2025. 7. 18. 22:09

1. ClientRegistration

  • OAuth 2.0 또는 OpenID Connect 1.0 제공자에 등록된 클라이언트 정보를 나타내는 객체

 

필드) 기본 필드

더보기
필드명 설명
registrationId 이 클라이언트를 구분할 수 있는 고유 ID google, okta
clientId OAuth 제공자에 등록된 클라이언트 ID  
clientSecret 클라이언트 시크릿  
clientAuthenticationMethod 클라이언트 인증 방식

client_secret_basic
client_secret_post
none
private_key_jwt
authorizationGrantType 인증 방식 (grant type)
authorization_code
client_credentials
password
urn:ietf:params:oauth:grant-type:jwt-bearer
redirectUri 로그인 이후 리디렉션될 URI {baseUrl}/login/oauth2/code/{registrationId}
scopes 요청할 권한 범위 openid, profile, email
clientName 이 클라이언트의 이름 로그인 버튼에 표시될 이름

 

필드) ProviderDetails

더보기
ProviderDetails 필드명 설명
authorizationUri 권한 요청 (authorization code 받기) 엔드포인트 URL
tokenUri 액세스 토큰 요청을 보낼 엔드포인트 URL
jwkSetUri 공개키(JWK Set)를 가져올 URI (ID Token 검증용)
issuerUri 제공자의 고유 식별자 URI
configurationMetadata OP의 .well-known/openid-configuration의 전체 메타데이터

 

필드) UserEndpoint

더보기
UserEndpoint 필드명 설명
uri 사용자 정보(UserInfo)를 요청할 수 있는 엔드포인트 URL  
authenticationMethod Access token을 전달하는 방식 header
form
query
userNameAttributeName 사용자 정보 응답 중 "사용자 식별자"로 쓸 속성 이름 sub
email

 

설정) 자동 구성 Discovery 사용

더보기
ClientRegistration clientRegistration =
    ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();

 

2. ClientRegistrationRepository

  • OAuth 2.0 / OpenID Connect 1.0 ClientRegistration들을 관리하고 제공하는 저장소 인터페이스

 

3. OAuth2AuthorizedClient

  • OAuth 2.0에서 리소스 소유자가 ClientRegistration에게 자신의 자원 접근을 허용한 "인증된 클라이언트"의 상태를 표현하는 객체
필드 설명
ClientRegistration 어떤 클라이언트에 대한 인증인가
Principal 어떤 사용자가 인증했는가
OAuth2AccessToken 발급받은 액세스 토큰
OAuth2RefreshToken (옵션) 리프레시 토큰이 있다면 포함

 

4. OAuth2AuthorizedClientRepository and OAuth2AuthorizedClientService

구성요소 사용 흐름 사용 컴포넌트 OAuth2AuthorizedClient 보관 위치
OAuth2AuthorizedClientRepository 웹 요청 필터, 컨트롤러 등 HttpSession
OAuth2AuthorizedClientService 애플리케이션 전역 서비스, 배치 등 InMemory or DB

 

구현체) OAuth2AuthorizedClientRepository

더보기
항목 HttpSessionOAuth2AuthorizedClientRepository
AuthenticatedPrincipalOAuth2AuthorizedClientRepository
저장 방식 HttpSession
인증된 사용자의 Principal 이름 기반
저장 위치 HttpSession 내부의 Map
OAuth2AuthorizedClientService
(예: InMemory, JDBC 등)
대상 세션을 사용하는 웹 사용자
인증 주체가 있는 환경
사용 환경 전통적인 웹 로그인 방식 server to server
stateless
예시 로그인한 사용자의 Access Token을 세션에 저장
인증된 사용자 또는 서버 앱의 토큰을 별도로 관리

 

구현체) OAuth2AuthorizedClientService

더보기
구현체 설명 비고
InMemoryOAuth2AuthorizedClientService 토큰 정보를 메모리에 저장함 서버 재시작 시 데이터 유실
JdbcOAuth2AuthorizedClientService 토큰 정보를 DB 에 저장함 사용자 정의 SQL 또는 스키마 커스터마이징 가능

 

5. OAuth2AuthorizedClientManager and OAuth2AuthorizedClientProvider

구성 요소 역할 처리 흐름 / 책임
OAuth2AuthorizedClientManager OAuth2 Client 인증 흐름을 제어하는 중앙 관리자 1. 인증 요청 생성
2. 인증
3. OAuth2AuthorizedClient 저장 or 삭제
OAuth2AuthorizedClientProvider grant type에 따른 토큰 발급/갱신 전략 객체
authorization_code
client_credentials
refresh_token
password

 


구현체) OAuth2AuthorizedClientManager

더보기
항목 DefaultOAuth2AuthorizedClientManager
AuthorizedClientServiceOAuth2AuthorizedClientManager
용도 웹 애플리케이션에서 사용자 기반 인증 흐름 처리
세션이 없는 환경에서 사용
토큰 저장소 타입 OAuth2AuthorizedClientRepository
OAuth2AuthorizedClientService
세션 사용 여부
기반 정보 HttpServletRequest
Authentic
ation
Authentication.getName()
ClientRegistrationId
사용 사례 로그인된 사용자의 at 발급/갱신/보관
백엔드 서비스 호출, 스케줄러, 백그라운드 작업에서 at 요청
기본 구성 요소 여부 Spring Security 웹 환경에서 자동 구성됨
별도 Bean 등록 필요

 

커스터마이징) OAuth2AuthorizedClientManager

더보기

웹 환경용

@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
        ClientRegistrationRepository repo,
        OAuth2AuthorizedClientRepository repository) {

    OAuth2AuthorizedClientProvider provider =
        OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build();

    DefaultOAuth2AuthorizedClientManager manager =
        new DefaultOAuth2AuthorizedClientManager(repo, repository);
    manager.setAuthorizedClientProvider(provider);

    return manager;
}

 

서비스 애플리케이션용

@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
        ClientRegistrationRepository repo,
        OAuth2AuthorizedClientService service) {

    OAuth2AuthorizedClientProvider provider =
        OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build();

    AuthorizedClientServiceOAuth2AuthorizedClientManager manager =
        new AuthorizedClientServiceOAuth2AuthorizedClientManager(repo, service);
    manager.setAuthorizedClientProvider(provider);

    return manager;
}

 

커스터마이징) contextAttributesMapper

더보기
manager.setContextAttributesMapper(authorizeRequest -> {
    HttpServletRequest request = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
    attributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
    return attributes;
});

 

구현체) OAuth2AuthorizedClientProvider

더보기
Provider 구현체 grant type
설명
Server-to-Server
AuthorizationCodeOAuth2AuthorizedClientProvider authorization_code 로그인 후 받은 code로 access_token 발급
RefreshTokenOAuth2AuthorizedClientProvider refresh_token access_token 갱신
TokenExchangeOAuth2AuthorizedClientProvider token-exchange access_token → 다른 시스템 토큰 교환 🔁 중간 형태
ClientCredentialsOAuth2AuthorizedClientProvider client_credentials client-secret  access_token 발급
JwtBearerOAuth2AuthorizedClientProvider jwt-bearer jwt assertion 기반 access_token 발급
DelegatingOAuth2AuthorizedClientProvider 여러 전략 결합 여러 Provider를 순차 위임하여 처리
(grant_type에 따라 적절한 전략을 선택)
-

 

커스터마이징) OAuth2AuthorizedClientProvider

더보기
OAuth2AuthorizedClientProvider provider =
    OAuth2AuthorizedClientProviderBuilder.builder()
        .authorizationCode()		// grant: authorization_code
        .refreshToken()			// grant: refresh_token
        .clientCredentials()		// grant: client_credentials
        .password()			// grant: password
        .build();
  • builder 패턴으로 생성 (grant type에 해당하는 전략 객체를 생성하기 위해 순차적으로 설정함)
  • 위에 설정한 전략들을 하나의 DelegatingOAuth2AuthorizedClientProvider 로 조합하여 반환

 

 

출처