Spring/Spring Security

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

noahkim_ 2025. 7. 18. 22:09

1. ClientRegistration

  • OAuth 2.0 또는 OpenID Connect Provider에 등록된 하나의 OAuth2 Client 설정을 표현하는 객체

 

필드) 기본 필드

더보기
필드명 설명
registrationId 이 클라이언트를 구분할 수 있는 고유 ID google, okta
clientId OAuth 제공자에 등록된 클라이언트 ID <provider>가 발급함
clientSecret 클라이언트 시크릿 <provider>가 발급함
clientAuthenticationMethod 클라이언트 인증 방식 client_secret_basic
client_secret_post
private_key_jwt
none
authorizationGrantType 인증 방식 (grant type)
authorization_code
client_credentials
password
urn:ietf:params:oauth:grant-type:jwt-bearer
redirectUri 인증 완료 후 Provider가 브라우저를 돌려보낼 Callback URI {baseUrl}/login/oauth2/code/{registrationId}
scopes 클라이언트가 요청할 권한 범위 openid, profile, email
clientName 이 클라이언트의 이름 로그인 버튼에 표시될 이름

 

필드) ProviderDetails

더보기
  • 상대 Authorization Server 또는 OIDC Provider와 통신하기 위한 정보
ProviderDetails 필드명 설명
authorizationUri 사용자를 보내 로그인과 동의를 수행하고 Authorization Code를 받는 Endpoint
tokenUri Authorization Code 등을 Access Token으로 교환하는 Endpoint
jwkSetUri JWT 서명을 검증할 공개키 집합을 조회하는 URI
issuerUri Provider를 식별하는 issuer URI
configurationMetadata Discovery 문서에서 조회한 추가 Provider 메타데이터

 

필드) 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

  • 특정 OAuth2 Client가 사용자 또는 클라이언트 주체의 권한으로 Access Token을 발급받은 상태를 표현하는 객체
필드 설명
ClientRegistration 토큰을 발급받은 OAuth2 Client의 등록 정보
PrincipalName 해당 인가와 연결된 사용자 또는 클라이언트 주체의 이름
OAuth2AccessToken 발급받은 AccessToken
OAuth2RefreshToken (옵션) 발급받은 RefreshToken

 

4. OAuth2AuthorizedClientRepository and OAuth2AuthorizedClientService

  • OAuth2AuthorizedClient를 저장하고 조회하는 클래스
  • 사용되는 실행 환경이 다름
구성 요소 중심 환경 특징
OAuth2AuthorizedClientRepository 현재 Servlet 웹 요청 HttpServletRequest, HttpServletResponse, Authentication을 기반으로 조회·저장
OAuth2AuthorizedClientService 애플리케이션 서비스 계층 registrationIdprincipalName을 기반으로 조회·저장

 

구현체) 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. ClientRegistration 조회
2. 기존 OAuth2AuthorizedClient 조회
3. 기존 Access Token 재사용 가능 확인
4. Provider에 최초 인가 또는 재인가 위임
5. 발급된 OAuth2AuthorizedClient 저장
6. 실패 시 삭제 또는 실패 처리
OAuth2AuthorizedClientProvider grant type에 따른 토큰 발급/갱신 전략 객체
authorization_code
client_credentials
refresh_token
password

 


구현체) OAuth2AuthorizedClientManager

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

 

커스터마이징) 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 로 조합하여 반환

 

 

출처