테마.log/Clone project

[Web Service Project]9.Spring Security & OAuth 2.0 로그인

_2J 2021. 3. 31. 14:22
  • 스프링 시큐리티 개념
  • SpringBoot 1.5와 2.0의 차이
  • 구글 서비스 등록

스프링 시큐리티(Spring Security)

  • 인증(Authentication)와 인가(Authorization) 기능을 가진 프레임워크
  • 스프링 기반의 어플리케이션에서는 보안을 위한 표준
  • 인터셉터, 필터 기반의 보안 기능을 구현하는 것보다 스프링 시큐리티를 통해 구현하는 것을 권장

스프링 시큐리티와 스프링 시큐리티 OAuth2 클라이언트

  • 직접 구현하는 경우 개발해야할 기능
    • 로그인 시 보안
    • 비밀번호 찾기
    • 비밀번호 변경
    • 회원가입 시 이메일 혹은 전화번호 인증
    • 회원정보 변경
  • OAuth 로그인 구현 시 위 목록들을 모두 구글, 페이스북, 네이버 등에 맡겨 서비스 개발에 집중

Spring Boot 2.0의 OAuth 2.0 설정 방법

  • OAuth2 설정
    • spring-security-oauth2-autoconfigure 라이브러리는 Spring Boot2에서도 1.5에서 쓰던 설정을 사용할 수 있다.
      • 기존에 사용되던 방식은 확장 포인트가 적절하게 오픈되어있지 않아 직접 상속하거나 오버라이딩 해야 하고, 신규 라이브러리의 경우 확장 포인트를 고려해서 설계된 상태
    • 여기서는 Spring Security Oauth2 Client 라이브러리 사용
      • 기존 1.5 에서 사용되던 spring-security-oauth 프로젝트는 신규 기능 없이 유지
      • 신규 기능은 새 oauth2 라이브러리에서만 지원
  • 스프링 부트용 라이브러리(starter) 출시
  • 스프링 부트2.0 security 설정 정보 확인 방법
    • spring-security-oauth2-autoconfigure 라이브러리 확인
    • application.properties 혹은 application.yaml 정보에 차이 비교

 

SpringBoot 1.5 버전 설정
google:  
  client:  
    clientId: 인증정보  
    clientSecret: 인증정보  
    accessTokenUrl: {url}  
    userAuthorizationUrl: {url}  
    clientAuthenticationScheme: form  
    scope: email, profile  
  resource:  
    userInfoUrl: {url}

 

SpringBoot 2.x 버전 설정
spring:  
  security:  
    oauth2:  
      client:  
        clientId: 인증정보  
        clientSecret: 인증정보

 

  • SpringBoot 1.5 vs 2.x
    • 1.5 방식에서는 url 주소를 모두 명시해야 하지만, 2.0 방식에서는 client 인증 정보만 입력하면 된다.
    • 1.5 버전에서 직접 입력했던 값들은 2.0버전으로 오면서 모두 emum으로 대체 되었다.
    • CommonOAuth2Provider에서 구글, 깃허브, 페이스북, 옥타(Okta)의 기본 설정 값을 제공한다.
    • 이외 다른 소셜 로그인(naver, kakao)을 추가한다면 직접 다 추가 해야 한다.
public enum CommonOAuth2Provider {

    GOOGLE {

        @Override
        public Builder getBuilder(String registrationId) {
            ClientRegistration.Builder builder = getBuilder(registrationId,
                    ClientAuthenticationMethod.BASIC, DEFAULT_REDIRECT_URL);
            builder.scope("openid", "profile", "email");
            builder.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
            builder.tokenUri("https://www.googleapis.com/oauth2/v4/token");
            builder.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs");
            builder.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo");
            builder.userNameAttributeName(IdTokenClaimNames.SUB);
            builder.clientName("Google");
            return builder;
        }
    },
    // ... 
}

구글 서비스 등록

  • 구글 서비스 신규 서비스 생성
    • 발급된 인증 정보(clientId, clientSecret)을 통해 로그인 기능과 소셜 서비스 기능을 사용
  • 프로젝트에 OAuth 설정 적용
    • resources 디렉토리에 application-oauth.properties 파일 생성

  • application-oauth.properties 파일 내에 구글 OAuth 설정
    • 클라이언트 ID 값 설정
    • 클라이언트 보안 값 설정
    • scope는 profile, email을 강제 설정
      • 기본값은 openId, profile, email 이다.
      • 하지만 openId를 그대로 설정하는 경우 Open Id Provider로 인식하게 된다.
      • 그리할 경우 OpenId Provider인 서비스(구글)와 그렇지 않은 서비스(Naver, Kakao 등) 나눠서 OAuth2Service를 만들어야 한다.
      • 하나의 OAuth2Sercice를 사용하기 위해 openId scope를 제외한다.
spring.security.oauth2.client.registration.google.client-id={clientId} 
spring.security.oauth2.client.registration.google.client-secret={clientSecret} 
spring.security.oauth2.client.registration.google.scope=profile,email
  • application.properties 파일에서 application-oauth.properties를 포함하도록 구성
    • 스프링 부트에서는 properties의 이름을 application-xxx.properteis로 만들면 xxx라는 이름의 profile이 생성되어 이를 통해 관리할 수 있다.
    • 즉, profile=xxx라는 식으로 호출하면 해당 properties의 설정들을 가져올 수 있다.
    • 여기선 스프링 부트의 기본 설정파일인 application.properties, application-oauth.properties를 포함하도록 구성한다.
  • application.properties 파일 내 설정 추가
spring.profiles.include=oauth