[SpringBoot] Spring Security #2 OAuth2

2022. 11. 20. 16:51JAVA/Spring

1. Client

만약 클래스패스에 spring-security-oauth2-client 프로퍼티가 설정되어 있다면, OAuth2/Open ID 클라이언트 연결에 자동 설정에 대한 이점을 가질 수 있습니다. 이 설정은 OAuth2ClientProperties 아래의 속성을 사용합니다. 서블릿 및 리액티브 애플리케이션 모두에 동일한 속성이 적용됩니다. 

 

spring.security.oauth2.client 접두어하에 여러개의 OAuth2 client와 provider를 등록할 수 있습니다. 다음 예제와 같이 등록할 수 있습니다.

spring:
  security:
    oauth2:
      client:
        registration:
          my-client-1:
            client-id: "abcd"
            client-secret: "password"
            client-name: "Client For user scope"
            provider: "my-oauth-provider"
            scope: "user"
            redirect-uri: "https://my-redirect-uri.com"
            client-authentication-method: "basic"
            authorization-grant-type: "authorization-code"

          my-client-2:
            client-id : "abcd"
            client-secret: "password"
            client-name: "Client for email scope"
            provider: "my-oauth-provider"
            scope: "email"
            redirect-uri: "https://my-redirect-uri.com"
            client-authentication-method: "basic"
            authorization-grant-type: "authorization-code"
        provider:
          my-oauth-provider:
            authorization-uri: "https://my-auth-server/oauth/authorize"
            token-uri: "https://my-auth-server/oauth/token"
            user-info-uri: "https://my-auth-server/userinfo"
            user-info-authentication-method: "header"
            jwk-set-uri: "https://my-auth-server/token_keys"
            user-name-attribute: "name"

OpenID Connect discovery를 지원하는 OpenID Connect providers를 위한 설정은 더욱 단순화될 수 있습니다. provider는 issuer-uri를 설정하는 것이 필요하다. 예를 들어 issuer-uri가 "https://example.com"라면 OpenID Provider Configuration Request는 "https://example.com/.well-known/openid-configuration"으로 만들 것입니다.

 

다음 예제는 OpenID Connect Provider가 어떻게 issuer-uri를 설정하는지 보여줍니다.

spring:
  security:
    oauth2:
      client:
        provider:
          oidc-provider:
            issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/"

기본적으로 Spring Security의 OAuth2LoginAuthenticationFilter는 오직 "/login/oauth2/code/*" URL 매칭만을 처리합니다. 만약 다른 패턴으로 사용하기 위해서 redirect-uri를 커스터마이징 하고 싶다면 커스텀 패턴을 처리하기 위한 설정이 필요합니다. 예를 들어 서블릿 애플리케이션에서 SecurityFilterChain을 다음과 같이 추가할 수 있습니다.

@Configuration
public class MyOAuthClientConfiguration {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
        http.oauth2Login((login) -> login.redirectionEndpoint().baseUri("custom-callback"));
        return http.build();
    }
}

 

공통 provider에 대한 OAuth2 클라이언트 등록(OAuth2 client registration for common providers)

구글, 깃허브, 페이스북, 오카타를 포함한 공통 OAuth2와 OpenID provider는 기본값 제공자 집합을 제공합니다.

 

만약 이러한 providers들의 커스터마이징이 필요하지 않다면 기본값으로 provider 속성을 설정할 수 있습니다. 또한 만약 클라이언트 등록에 대한 키(key)가 기본적인 provider 지원에 매칭된다면 스프링부트가 유추할 수 있습니다. 

 

다음 예제의 두 설정은 Google provider를 사용합니다.

spring:
  security:
    oauth2:
      client:
        registration:
          my-client:
            client-id: "abcd"
            client-secret: "password"
            provider: "google"
          google:
            client-id: "abcd"
            client-secret: "password"

 

2. Resource Server

만약 클래스패스에 spring-security-oauth2-resource-server 프로퍼티가 설정되어 있다면, Spring Boot는 OAuth2 Resource Server를 설정할 수 있습니다. JWT 설정의 경우 다음 예와 같이 JWK Set URI 또는 OIDC Issuer URI를 명세해야 합니다. 

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jwk-set-uri: "https://example.com/oauth2/default/v1/keys"
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: "https://dev-123456.oktapreview.com/oauth2/default/"

 

서블릿과 리액티브 애플리케이션 모두에 동일한 속성을 적용할 수 있습니다. 또는 서블릿 애플리케이션을 위한 JwtDecoder 빈이나 리액티브 애플리케이션을 위한 ReactiveJwtDecoder 빈을 정의 할 수 있습니다.

 

JWT 대신 opaque 토큰이 사용되는 경우 다음 속성을 설정하여 내부 검사를 통해 토큰의 유효성을 검사할 수 있습니다.

spring:
  security:
    oauth2:
      resourceserver:
        opaquetoken:
          introspection-uri: "https://example.com/check-token"
          client-id: "my-client-id"
          client-secret: "my-client-secret"
  • 서블릿 애플리케이션과 리액티브 애플리케이션에 동일한 속성을 적용될 수 있음
  • opaque 토큰 대신 서블릿 애플리케이션에서는 OpaqueTokenIntrospector 빈을 정의할 수 있고 리액티브 애플리케이션에서는 ReactiveOpaqueTokenIntrospector 빈을 정의할 수 있음

 

3. Authorization Server

Spring Security는 OAuth 2.0 인증 서버를 구현하는 것을 지원하지 않습니다. 그러나 이 기능은 Spring Security OAuth 프로젝트에서 사용할 수 있으며, 이 프로젝트는 결국 Spring Security로 대체될 예정입니다. 그때까지 spring-security-oauth2-autoconfigure 모듈을 사용하여 OAuth 2.0 인증 서버를 쉽게 설정할 수 있습니다.

https://docs.spring.io/spring-security-oauth2-boot/docs/current/api/

 

Generated Documentation (Untitled)

 

docs.spring.io

 

References

https://docs.spring.io/spring-boot/docs/2.7.2/reference/htmlsingle/#web.security.oauth2