OAuth2 Naver Login

Naver API 등록

스프링 시큐리티 설정 등록

application-oauth.yml

  • 네이버에서는 스프링 시큐리티를 공식 지원하지 않으므로 설정 추가

    • CommonOAuth2Provider에서 해주던 값들도 전부 수동으로 입력
    1. user_name_attribute: response
      • 기준이 되는 user_name의 이름을 네이버에서는 response로 해야 한다.
      • 네이버의 회원 조회시 반환되는 JSON 형태 때문이다.
      • 스프링 시큐리티에서는 하위 필드를 명시할 수가 없다.
      • 최상위 필드로 사용할 수 있는 값은 resultCode, message, response이다.
      • 최상위 필드만 user_name으로 지정이 가능하능하기 때문에 필요한 값인 response 값을 설정
  • 네이버 프로필 조회 API 호출 결과 값

    • response라는 key값의 value 값이 사용자 정보의 값이다.
{
  "resultcode": "00",
  "message": "success",
  "response": {
    "email": "openapi@naver.com",
    "nickname": "OpenAPI",
    "profile_image": "https://ssl.pstatic.net/static/pwe/address/nodata_33x33.gif",
    "age": "40-49",
    "gender": "F",
    "id": "32742776",
    "name": "오픈 API",
    "birthday": "10-01"
  }
}
  • application-oauth.yml 파일 설정
# google oauth2 setting
spring:
  security:
    oauth2:
      client:
        # registration
        registration:
          # GOOGLE oauth2 setting
          google:
            client-id: {...}
            client-secret: {...}
            scope:
              - profile
              - email

          # NAVER oauth2 setting
          naver:
            client-id: {...}
            client-secret: {...}
            redirect_uri_template: {baseUrl}/{action}/oauth2/code/{registrationId}
            authorization_grant_type: authorization_code
            scope:
              - name
              - emaiL
              - profile_image
            client-name: Naver

        # provider
        provider:
            naver:
              authorization_uri: https://nid.naver.com/oauth2.0/authorize
              token_uri: https://nid.naver.com/oauth2.0/token
              user-info-uri: https://openapi.naver.com/v1/nid/me
              user_name_attribute: response

OAuthAttributes

  • OAuth의 사용자 정보를 가져올 Dto
    • Naver Attributes 추가
@Getter
public class OAuthAttributes {
    // ...

    public static OAuthAttributes of(
            String registrationId
            , String userNameAttributeName
            , Map<String, Object> attributes) {
        if("naver".equals(registrationId)) {
            return ofNaver("id", attributes);
        }
        return ofGoogle(userNameAttributeName, attributes);
    }

    private static OAuthAttributes ofNaver(String userNameAttributeName, Map<String, Object> attributes) {
        Map<String, Object> response = (Map<String, Object>) attributes.get("response");

        return OAuthAttributes.builder()
                .name((String) response.get("name"))
                .email((String) response.get("email"))
                .picture((String) response.get("profileImage"))
                .attributes(response)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }

    // ...
}

index.mustache

  • login button

    1. /oauth2/authorization/naver

      • 네이버 로그인 URL은 application-oauth.yml에 등록한 redirect_uri_template 값에 맞춰서 자동으로 등록된다.
      • /oauth2/authorization/ 까지는 고정, 마지막 Path만 각 소셜 로그인 코드를 사용
      • naver가 마지막 Path가 된다.
{{>layout/header}}

    <h1>스프링 부트로 시작하는 웹 서비스 No. 3</h1>

    <div class="col-md-12">
        <div class="row">
            <div class="col-md-6">
                <a href="/posts/save" role="button" class="btn btn-primary">글 등록</a>
                {{#userName}}
                    Logged in as: <span id="user">{{userName}}</span>
                    <a href="/logout" class="btn btn-info active" role="button">Logout</a>
                {{/userName}}
                {{^userName}}
                    <a href="/oauth2/authorization/google" class="btn btn-success active" role="button">Google Login</a>
                    <a href="/oauth2/authorization/naver" class="btn btn-secondary active" role="button">Naver Login</a>
                {{/userName}}
            </div>
        </div>
        <br>
        <!-- 목록 출력 영역 -->

    </div>

{{>layout/footer}}

네이버 로그인 확인

이슈

  • 기존 설정된 application-oauth.yml 파일에 naver 설정을 추가하였더니 안됨
  • 다시 properties 파일로 변경하니 정상적으로 됨, 확인해봐야 하는 문제

세션 관리 하기

  • 현재 서비스에서는 어플리케이션을 재실행하면 로그인이 풀리게 된다.

    • 이유는 세션이 내장 톰캣의 메모리에 저장되기 때문이다.
    • 기본적으로 세션은 실행되는 WAS(Web Application Server)의 메모리에서 저장되고 호출된다.
    • 메모리에 저장되다보니 내장 톰캣처럼 어플리케이션 실행 시 실행되는 구조에서 항상 초기화가 된다.
    • 즉, 배포할 때마다 톰캣이 재시작된다.
    • 만약 2대 이상의 서버에서 서비스하는 경우 톰캣마다 세션 동기화 설정을 해야 한다.
  • 실제 현업에서 사용하는 3가지 세션 저장소

    1. 톰캣 세션 사용
      • 일반적으로 별다른 설정을 하지 않을 때 기본적으로 선택되는 방식
      • 톰캣(WAS)에 세션이 저장되기 때문에 2대 이상의 WAS가 구동되는 환경에서는 톰캣들 간의 세션 공유를 위한 추가 설정이 필요
    2. MySQL과 같은 데이터베이스를 세션 저장소로 사용
      • 여러 WAS 간의 공용 세션을 사용할 수 있는 가장 쉬운 방법
      • 많은 설정이 필요 없지만, 결국 로그인 요청마다 DB IO가 발생하여 성능상 이슈가 발생할 수 있다.
      • 보통 로그인 요청이 많이 없는 백오피스, 사내 시스템 용도에서 사용
    3. Redis, Memcached와 같은 메모리 DB를 세션 저장소로 사용
      • B2C 서비스에서 가장 많이 사용하는 방식
      • 실제 서비스로 사용하기 위해서는 Embedded Redis와 같은 방식이 아닌 외부 메모리 서버가 필요

Spring Session 설정

의존성 추가

  • build.gradle 내에 spring-session-jdbc 의존성 추가
dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.projectlombok:lombok")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.h2database:h2")
    compile('org.springframework.boot:spring-boot-starter-mustache')
    compile('org.springframework.boot:spring-boot-starter-oauth2-client')
    compile("org.springframework.session:spring-session-jdbc")

    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.security:spring-security-test')
}

properties 파일 내에 추가

  • 세션 저장소를 jdbc로 선택하도록 코드 추가
# jpa setting
spring:
  profiles:
    include: oauth # oauth 관련 properties 추가
  session:
    store-type: jdbc

Session 설정 테스트

  • h2-console 내에 테이블 추가 확인
    • jpa로 인하여 세션 테이블이 자동생성
    • spring_session
    • spring_session_attributes
    • 한 개의 세션 등록 확인
    • 여전히 H2 데이터베이스 기반의 스프링 부트 프로젝트이기 때문에 나중에 AWS의 RDS 서비스를 사용하는 경우 적용확인 가능

  • 로그인 후 테이블 내용 확인

spring_session 테이블
spring_session_attributes 테이블

Intellij Tools

  • General ShortCut
ShortCut 설명
ctrl + alt + s 설정창(settings) 열기
ctrl + alt + shift + s Project Structure 창 열기
ctrl + e 최근 사용한 파일 목록 조회
ctrl + shift + a 액션을 검색하여 실행 (설정 변경 및 단축키 확인)
double shift 파일, 클래스, 설정 등 키워드 관련 검색
  • Search
ShortCut 설명
ctrl + shift + n 파일 검색
ctrl + alt + shift + n 메서드 검색
ctrl + e 최근 파일 목록 보기
ctrl + shift + e 최근 수정한 파일 목록 보기
  • Editor ShortCut
ShortCut 설명
ctrl + f4 탭 닫기
ctrl + space 코드 완성
alt + insert 코드 생성 (constructor, getter, setter, override method)
ctrl + o override 메서드 확인
ctrl + i implements method 확인
ctrl + q document 확인
ctrl + d copy line
ctrl + y delete line
alt + shift + ↑ ↓ 라인 단위로 옮기기
ctrl + shift + ↑ ↓ 구문 안에서 라인 옮기기
  • Code View
ShortCut 설명
ctrl + p 인자 값 보기 (Parameter Info)
ctrl + shift + i 코드 구현부 보기 (Quick Definition)
ctrl + ←→ 단어별 이동
ctrl + shift + ←→ 단어별 선택
  • Focus
ShortCut 설명
ctrl + w 포커스 범위 한 단계씩 늘리기
ctrl + shift + w 포커스 범위 한 단계씩 줄이기
ctrl + alt + ←→ 포커스 앞 / 뒤로 이동
double ctrl + ↑ ↓ 멀티 포커스
F2 오류 라인 포커스

'tools > IntelliJ' 카테고리의 다른 글

[IntelliJ] Auto import  (0) 2020.06.08
[IntelliJ] Build Automatically  (0) 2020.05.31

Build Automatically 사용하기

이클립스 설정

  • Tomcat 서버 켠 상태에서 자바 코드 수정 시 자동으로 Build 해주는 역할

인텔리제이 설정

  • Compiler > Build project automatically 체크
  • Registry > complier.automake.allow.when.app.running 체크
  1. Compiler > "Build project automatically" 체크
    • not running / debugging 시에만 작동

  1. *Actions 열기 > Registry *

-  **compiler.automake.allow.when.app.running 체크**

'tools > IntelliJ' 카테고리의 다른 글

[IntelliJ] Auto import  (0) 2020.06.08
[IntelliJ] 단축키(Short Cut)  (0) 2020.06.01

어노테이션 기반으로 개선하기

  • 반복되는 같은 코드 해결하기
    • 커스텀 어노테이션(@LoginUser) 만들기
    • ArgumentResolver

커스텀 어노테이션 생성

  • 세션 처리를 위한 @LoginUser 어노테이션 생성
    1. @Target(ElementType.PARAMETER)
      • 어노테이션이 생성될 수 있는 위치를 지정
      • PARAMETER로 지정하므로써 메서드의 파라미터로 선언된 객체에서만 사용될 수 있다.
      • 이 외에도 클래스 선언시 사용할 수 있는 TYPE 등이 있다.
    2. @Interface
      • 해당 파일을 어노테이션 클래스로 지정
      • LoginUser라는 이름을 가진 어노테이션을 사용할 수 있다.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}

LoginUserArgumentResolver

  • ArgumentResolver 생성

    • HandlerMethodArgumentResolver 인터페이스를 구현한 클래스
    • 조건에 맞는 경우 메서드가 있다면, HandlerMethodArguementResolver의 구현체가 지정한 값으로 해당 메서드의 파리미터로 넘길 수 있다.
    1. supportParameter()
      • 컨트롤러 메서드의 특정 파라미터를 지원하는지 판단
      • 파라미터에 @LoginUser 어노테이션이 붙어있고, 파라미터 클래스 타입이 SessionUser.class인 경우 true를 반환
    2. resolveArgument()
      • 파라미터에 전달할 객체를 생성
      • 해당 코드에서는 세션에서 객체를 가져온다.
@RequiredArgsConstructor
@Component
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

    private final HttpSession httpSession;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean isLoginUserAnnotation = parameter.getParameterAnnotation(LoginUser.class) != null;
        boolean isUserClass = SessionUser.class.equals(parameter.getParameterType());

        return isLoginUserAnnotation && isUserClass;
    }

    @Override
    public Object resolveArgument(
            MethodParameter parameter
            , ModelAndViewContainer mavContainer
            , NativeWebRequest webRequest
            , WebDataBinderFactory binderFactory) throws Exception {

        return httpSession.getAttribute("user");
    }
}

ArgumentResolver 설정

  • WebConfig
    • 스프링에서 LoginUserArgumentResolver를 인식할 수 있도록 WebMvcConfigurer를 구현한 WebConfig 클래스에 설정한다.
    • WebMvcConfigurer의 addArgumentResolvers()를 추가한다.
    • 다른 HandlerMethodArgumentResolver가 필요한 경우 같은 방식으로 추가한다.
@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final LoginUserArgumentResolver loginUserArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolver) {
        argumentResolver.add(loginUserArgumentResolver);
    }
}

Controller 수정

  • 세션을 사용하는 부분 수정

    • @LoginUser를 파라미터로 받아 사용할 수 있도록 수정
    1. @LoginUser SessionUser user
      • 기존 (SessionUser) httpSession.getAttribute("user")로 가져오던 세션 정보 값을 개선
      • 다른 컨트롤러에서 세션이 필요한 경우 @LoginUser를 사용하여 세션 정보를 가져올 수 있다.
@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;
    private final HttpSession httpSession;

    @GetMapping("/")
    public String index(Model model, @LoginUser SessionUser user) {
        model.addAttribute("posts", postsService.findAllDesc());

        if(user !=  null) {
            model.addAttribute("userName", user.getName());
        }
        return "index";
    }

    @GetMapping("/posts/save")
    public String postsSave() {
        return "posts-save";
    }

    @GetMapping("/posts/update/{id}")
    public String postsUpdate(@PathVariable Long id, Model model) {
        PostsResponseDto dto = postsService.findById(id);
        model.addAttribute("post", dto);
        return "posts-update";
    }
}

어노테이션 기반으로 변경하여 다시 세션 체크

  • 글 작성 테스트

  • 글 등록 확인

로그인 테스트

  • 화면에 로그인 버튼 추가하기 & 로그인 성공 시 사용자명 나타내기
  • 컨트롤러에서 사용자명 저장하여 화면으로 전달하기
  • DB 테이블 확인하기
  • 글쓰기로 권한 관리 확인

FrontEnd

index.mustache

  • 로그인 버튼

    1. {{#userName}}

      • mustache는 다른 언어와 같은 if문을 제공하지 않는다.
      • true / false 여부만 판단
      • mustache에 항상 최종 값을 넘겨줘야 한다.
      • userName이 있다면 userName을 노출하도록 구성
    2. a href="/logout"

      • 스프링 시큐리티에서 기본적으 제공하는 로그아웃 URL
      • 개발자가 별도로 URL에 해당하는 컨트롤러를 만들 필요가 없다.
      • SecurityConfig 클래스에서 URL을 변경할 순 있지만 기본 URL을 사용해도 충분하다.
    3. {{^userName}}

      • mustache에서 해당 값이 존재하지 않는 경우 ^를 사용
      • userName이 없다면 로그인 버튼을 노출하도록 구성
    4. a href="/oauth2/authorization/google"

      • 스프링 시큐리티에서 기본적으로 제공하는 로그인 URL
      • 로그아웃 URL과 마찬가지로 개발자가 별도의 컨트롤러를 생성할 필요가 없다.
    <h1>스프링 부트로 시작하는 웹 서비스 No. 3</h1>

    <div class="col-md-12">
        <div class="row">
            <div class="col-md-6">
                <a href="/posts/save" role="button" class="btn btn-primary">글 등록</a>
                {{#userName}}
                    Logged in as: <span id="user">{{userName}}</span>
                    <a href="/logout" class="btn btn-info active" role="button">Logout</a>
                {{/userName}}
                {{^userName}}
                    <a href="/oauth2/authorization/google" class="btn btn-success active" role="button">Google Login</a>
                    <a href="/oauth2/authorization/naver" class="btn btn-secondary active" role="button">Naver Login</a>
                {{/userName}}
            </div>
        </div>
        <!-- -->
    </div>

BackEnd

IndexController

  • 컨트롤러 수정
    1. (SessionUser) httpSession.getAttribute("user")
      • CustomOAuth2UserService에서 로그인 성공 시 세션에 SessionUser를 저장하도록 구성
      • 로그인 성공 시 httpSession.getAttribute("user")에서 값을 가져올 수 있다.
    2. if (user != null)
      • 세션에 저장된 값이 있을 때만 model에 userName으로 등록
      • 세션에 저장된 값이 있으면 model엔 아무런 값이 없는 상태이니 로그인 버튼이 보이게 된다.
@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;
    private final HttpSession httpSession;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("posts", postsService.findAllDesc());
        SessionUser user = (SessionUser) httpSession.getAttribute("user");

        if(user !=  null) {
            model.addAttribute("userName", user.getName());
        }
        return "index";
    }

    // save, update
}

OAuth2 Google 로그인 및 권한 테스트

화면 수정 확인

화면 수정 로그인 버튼 확인

OAuth2 Google 연동 확인

OAuth2 확인

로그인 확인

로그인 확인

DB 내에 로그인 확인

OAuth2 Google Login 확인

로그인 유저 Role 수정

로그인 유저 Role 'User'로 수정

User Role 'USER'로 변경 후 글 등록 테스트 확인

글 등록 확인

OAuth2 Google Login

스프링 시큐리티 설정

  • build.gradle에 스프링 시큐리티 관련 의존성 추가
    1. spring-boot-starter-oauth2-client
      • 소셜 로그인 등 클라이언트 입장에서 소셜 기능 구현 시 필요한 의존성
      • spring-boot-oauth2-client와 spring-security-oauth2-jose를 기본으로 관리
dependencies {
    // ...
    compile('org.springframework.boot:spring-boot-starter-oauth2-client')

    // test
}

사용자 관련 클래스 생성

  • Dto 분류
    • 권한
    • 사용자 정보

사용자 권한(User Authrization)을 위한 Role 클래스 생성

  • Role 클래스
    • 각 사용자의 권한을 관리할 Enum 클래스
    • 스프링 시큐리티에서는 권한 코드에 항상 "ROLE_" 이 앞에 있어야 한다.
    • 코드별 키 값을 ROLE_GUEST, ROLE_USER 등으로 지정
@Getter
@RequiredArgsConstructor
public enum Role {

    GUEST("ROLE_GUEST", "손님"),
    USER("ROLE_USER", "일반 사용자");

    private final String key;
    private final String title;
}

사용자 정보(User) 담당할 도메인 클래스 생성

  • User

    • @Enumerated(EnumType.STRING)

      • JPA를 이용해 데이터베이스로 저장할 때 Enum 값을 어떤 형태로 저장할지를 결정
      • 기본적으로 int로 된 숫자가 저장된다.
      • 숫자로 저장되면 데이터베이스로 확인할 때 그 값이 무슨 코드를 의미하는 지 알 수가 없다.
      • 문자열(EnumType.STRING)로 저장될 수 있도록 선언
@Getter
@NoArgsConstructor
@Entity
public class User extends BaseTimeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @Column
    private String picture;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Role role;

    @Builder
    public User(String name, String email, String picture, Role role) {
        this.name = name;
        this.email = email;
        this.picture = picture;
        this.role = role;
    }

    public User update(String name, String picture) {
        this.name = name;
        this.picture = picture;

        return this;
    }

    public String getRoleKey() {
        return this.role.getKey();
    }
}

사용자관련 CRUD 작업할 UserRepository 생성

  • UserRepositry
    • findByEmail
      • 소셜 로그인으로 반환되는 값 중 email을 통해 이미 생성된 사용자인지 처음 가입하는 사용자인지 판단하기 위한 메서드
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

시큐리티 관련 패키지 및 클래스 생성

  • config.auth 패키지 생성

    • 시큐리티 관련 클래스 관리

    • SessionUser

    • OAuthAttributes

    • CustomOAuth2UserService

    • SecurityConfig

SessionUser 생성

  • SessionUser

    • 인증된 사용자 정보를 저장하는 클래스
    • User클래스 내에 세션 정보를 가질 수 없는 이유
  • SessionUser 클래스의 이유

    • User 클래스에 Session을 저장하려는 경우, User 클래스에 직렬화를 하지 않았기 때문에 오류가 발생한다.
    • User 클래스에 직렬화 코드를 넣는다면 ?
      • User 클래스는 Entity 클래스이기 때문에 문제가 발생할 가능성이 높다.
      • Entity 클래스는 언제 다른 엔티티와 관계가 형성될 지 모르기 때문이다.
      • @OneToMany, @ManyToMany 등 자식 엔티티를 갖고 있다면 직렬화 대상에 자식들까지 포함되니 성능 이슈, 부수 효과가 발생할 확률이 높다.
      • 직렬화 기능을 가진 세션 DTO를 하나 추가로 만드는 것이 이후 운영 및 유지보수에 도움이 된다.
@Getter
public class SessionUser implements Serializable {
    private String name;
    private String email;
    private String picture;

    public SessionUser(User user) {
        this.name = user.getName();
        this.email = user.getEmail();
        this.picture = user.getPicture();
    }
}

OAuthAttributes 생성

  • OAuthAttributes 클래스
    1. of()
      • OAuth2User에서 반환하는 사용자 정보는 Map이기 때문에 값 하나하나를 변환해야 한다.
    2. toEntity()
      • User 엔티티를 생성
      • OAuthAttributes에서 엔티티를 생성하는 시점은 처음 가입할 때이다.
      • 가입할 때의 기본 권한을 GUEST로 주기 위해서 role 빌더 값에는 Role.GUEST를 사용
@Getter
public class OAuthAttributes {
    private Map<String, Object> attributes;
    private String nameAttributeKey;
    private String name;
    private String email;
    private String picture;

    @Builder
    public OAuthAttributes(Map<String, Object> attributes
            , String nameAttributeKey
            , String name
            , String email
            , String picture) {
        this.attributes = attributes;
        this.nameAttributeKey = nameAttributeKey;
        this.name = name;
        this.email = email;
        this.picture = picture;
    }

    public static OAuthAttributes of(
            String registrationId
            , String userNameAttributeName
            , Map<String, Object> attributes) {

        return ofGoogle(userNameAttributeName, attributes);
    }

    public static OAuthAttributes ofGoogle(
            String userNameAttributeName
            , Map<String, Object> attributes) {

        return OAuthAttributes.builder()
                .name((String) attributes.get("name"))
                .email((String) attributes.get("email"))
                .picture((String) attributes.get("picture"))
                .attributes(attributes)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }

    public User toEntity() {
        return User.builder()
                .name(name)
                .email(email)
                .picture(picture)
                .role(Role.GUEST)
                .build();
    }
}

CustomOAuth2UserService 생성

  • CustomOAuth2UserService
    1. registrationId
      • 현재 로그인 진행 중인 서비스를 구분하는 코드
      • 추후 네이버 로그인 연동 시에 네이버 로그인인지, 구글 로그인인지 구분하기 위한 값
    2. userNameAttributeName
      • OAuth2 로그인 진행 시 키가 되는 필드값을 이야기한다.
      • Primary Key와 같은 의미
      • 구글의 경우 기본적으로 코드를 지원하지만, 네이버 카카오 등은 기본 지원하지 않는다.
      • 구글의 기본 코드는 'sub'
      • 이후 네이버 로그인과 구글 로그인을 동시 지원할 때 사용
    3. OAuthAttributes
      • OAuth2UserService를 통해 가져온 OAuth2User의 attribute를 담을 클래스
      • 이후 네이버 등 다른 소셜 로그인도 이 클래스를 사용
    4. SessionUser
      • 세션에 사용자 정보를 저장하기 위한 Dto 클래스
@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    private final UserRepository userRepository;
    private final HttpSession httpSession;

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2UserService delegate = new DefaultOAuth2UserService();
        OAuth2User oAuth2User = delegate.loadUser(userRequest);

        String registrationId = userRequest.getClientRegistration().getRegistrationId();

        String userNameAttributeName = userRequest.getClientRegistration()
                .getProviderDetails()
                .getUserInfoEndpoint()
                .getUserNameAttributeName();

        OAuthAttributes attributes = OAuthAttributes.of(
                        registrationId
                        , userNameAttributeName
                        , oAuth2User.getAttributes());

        User user  = saveOrUpdate(attributes);

        httpSession.setAttribute("user", new SessionUser(user));

        return new DefaultOAuth2User(
                Collections.singleton(new SimpleGrantedAuthority(user.getRoleKey()))
                , attributes.getAttributes()
                , attributes.getNameAttributeKey());
    }

    private User saveOrUpdate(OAuthAttributes attributes) {
        User user = userRepository.findByEmail(attributes.getEmail())
                .map(entity -> entity.update(
                        attributes.getName()
                        , attributes.getPicture())
                ).orElse(attributes.toEntity());

        return userRepository.save(user);
    }
}

Security Config 클래스 생성

  • SecurityConfig 클래스
    1. @EnableWebSecurity
      • Spring Security 설정들을 활성화
    2. http.csrf().disable().headers().frameOptions().disable()
      • h2-console 화면을 사용하기 위해 해당 옵션을 disable
    3. .authorizeRequests()
      • URL별 권한관리를 설정하는 옵션의 시작점
      • authorizeRequests가 선언되어야 antMatchers 옵션 사용 가능
    4. .antMatchers()
      • 권한 관리 대상을 지정하는 옵션
      • URL, HTTP 메서드 별로 관리가 가능
      • "/" 등 지정된 URL들은 permitAll() 옵션을 통해 전체 열람 권한 부여
      • POST 메서드이면서 "/api/v1/**" 주소를 가진 API는 USER 권한을 가진 사람만 가능하도록 부여
    5. andRequest
      • 설정된 값을 이외 나머지 URL들을 나타낸다.
      • 여기서는 authenticated() 추가하여 나버지 URL들은 모두 인증된 사용자들에게만 허용하도록 한다.
      • 인증된 사용자 즉, 로그인한 사용자들을 이야기 함
    6. logout().logoutSuccessUrl("/")
      • 로그아웃 기능에 대한 여러 설정의 진입점
      • 로그아웃 성공 시 "/" 주소로 이동
    7. oauth2Login
      • OAuth2 로그인 기능에 대한 여러 설정의 진입점
    8. userInfoEndpoint
      • OAuth2 로그인 성공 이후 사용자 정보를 가져올 때의 설정들을 담당
    9. userService
      • 소셜 로그인 성공 시 후속 조치를 진행할 UserService 인터페이스의 구현체를 등록
      • 리소스 서버(즉, 소셜 서비스들)에서 사용자 정보를 가져온 상태에서 추가로 진행하고자 하는 기능을 명시할 수 있다.
@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomOAuth2UserService customOAuth2UserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .headers().frameOptions().disable()
            .and()
                .authorizeRequests()
                .antMatchers("/"
                    , "/css/**"
                    , "/images/**"
                    , "/js/**"
                    , "/h2-console/**"
                ).permitAll()
                .antMatchers("/api/v1/**").hasRole(Role.USER.name())
                .anyRequest().authenticated()
            .and()
                .logout()
                .logoutSuccessUrl("/")
            .and()
                .oauth2Login()
                .userInfoEndpoint()
                .userService(customOAuth2UserService);
    }
}
  • 스프링 시큐리티 개념
  • 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)을 통해 로그인 기능과 소셜 서비스 기능을 사용

Google Cloud Platform

  • 프로젝트 선택

구글 클라우드 플랫폼

  • 새 프로젝트

새 프로젝트

  • 프로젝트 서비스 명 입력

등록될 서비스의 이름 입력

  • API 및 서비스 카테고리 -> 사용자 인증 정보

API 및 서비스 -> 사용자 인증 정보

  • 사용자 인증 정보 만들기 -> OAuth 클라이언트 ID

OAuth 클라이언트 ID

  • 다시 OAuth 클라이언트 ID 만들기 페이지로 이동

동의 화면 구성

  • Type 선택 (외부 선택 밖에 안됨)

  • 어플리케이션 이름 작성, Google API 범위 확인
    • 어플리케이션 이름
      • 구글 로그인 시 사용자에게 노출될 어플리케이션 이름
    • 지원 이메일
      • 사용자 동의 화면에서 노출될 이메일 주소
    • Google API의 범위
      • 구글 서비스에서 사용할 범위 목록
      • 기본값은 email, profile, openId (다른 정보 사용시 추가 가능)

동의 화면 구성

  • OAuth 클라이언트 ID 페이지 이동

  • OAuth 클라이언트 ID 만들기 페이지 이동
    • 어플리케이션 유형 선택
    • 프젝트명 입력
    • [승인된 리다이렉션 URL] 추가
      • 스프링 부트 시큐리티에서 기본적으로 {domain}/login/oauth2/code/{소셜서비스코드}로 리다이렉트
      • 현재 소셜서비스코드는 'google'
      • 서비스에서 파라미터로 인증 정보를 주었을 때, 인증이 성공하면 구글에서 리다이렉트할 URL
      • 시큐리티에서 구현되어 있기 때문에, 사용자가 별도로 리다이렉트 URL을 지원하는 Controller를 만들 필요가 없다.
      • AWS 서버에 배포할 경우 localhost 외에 주소를 추가해야 한다.
      • 현재는 로컬에서 개발하기 때문에 http://localhost:8085/login/oauth2/code/google 등록

  • 완료 후 클라이언트 ID, 클라이언트 Secret 확인
    • 해당 값들을 프로젝트에 설정해야 한다.

  • OAuth 2.0 클라이언트 ID 생성 확인

  • 생성된 클라이언트 ID 접근 해보면 서비스에 클라이언트 ID, 클라이언트 Secret 생성된 것을 확인 가능

  • 프로젝트에 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

'Spring > SpringBoot' 카테고리의 다른 글

[SpringBoot] 로그인 & 포스팅 권한 테스트  (0) 2020.05.31
[SpringBoot] OAuth2 Google Login  (0) 2020.05.31
[SpringBoot] 게시글 삭제  (0) 2020.05.29
[SpringBoot] 게시글 수정  (0) 2020.05.29
[SpringBoot] 게시글 전체 조회  (0) 2020.05.29

+ Recent posts