[SpringSecurity] 네이버 로그인 API 연동하기

Kaite.Kang·2023년 1월 22일
0
post-thumbnail

* 목표

네이버 로그인을 추가해보자.

구글 로그인을 등록하면서 대부분 코드가 확장성 있게 작성되었기 때문에 쉽게 등록이 가능하다.

1. 네이버 API 등록

먼저 네이버 오픈 API에서 프로젝트를 등록한다.

등록할 설정값은 다음과 같다.

2. 네이버 로그인 로직 설계

네이버 오픈 API의 호그인 회원 결과를 보고 어떤 데이터가 필요한지, 데이터를 어떻게 가공할지, 로직은 어떻게 구성할지 생각해보자.

{
  "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",
    "birthyear": "1900",
    "mobile": "010-0000-0000"
  }
}

우리 프로그램에서는 위 응답값 중에 name, email, profile_image 데이터가 필요하다.

스프링 시큐리티는 user와 password 값을 기본적으로 지원해 주는데 이는 재정의하여 사용할 수 있다. 하지만 스프링 시큐리티는 최상위 필드만 user로 지정 가능하며, 하위 필드는 지정할 수 없다. 네이버 응답값 최상위 필드는 resultCode, message, response이며 필요한 응답값들은 response의 하위 필드로 명시되어 있다.

우선 임시로 response를 user_name으로 재정의하고(1), 이후 자바 코드로 response의 id를 user_name으로 지정하여 해결할 수 있다.(2)

(1) application-oauth.properties 에서 user_name을 response로 재정의
(2) 서비스 레벨에서 구현

3. OAuth 설정값 등록

네이버 서비스 등록이 완료한 후에 받은 키값을 application-oauth.properties 에 등록한다.

  • src/main/resources/application-oauth.properties
##NAVER
#registration
spring.security.oauth2.client.registration.naver.client-id=클라이언트ID
spring.security.oauth2.client.registration.naver.client-secret=클라이언트시크릿
spring.security.oauth2.client.registration.naver.redirect-uri={baseUrl}/{action}/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.naver.scope=name,email,profile_image
spring.security.oauth2.client.registration.naver.client-name=Naver

#provider
spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize
spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token
spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me
spring.security.oauth2.client.provider.naver.user-name-attribute=response

네이버는 스프링 부트를 지원하지 않아서 그동안 CommonOAuth2Provider에서 해주던 값들을 수동으로 입력해 주어야 한다.

2. 스프링 시큐리티 설정 등록

네이버인지 판단하는 코드와 네이버 생성자를 추가하였다.

  • com/spring/book/config/auth/dto/OAuthAttributes.java
@Getter
public class OAuthAttributes {
    private Map<String, Object> attributes;
    private String nameAttributeKey;
    private String name;
    private String email;
    private String picture;

    ...

    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("profile_image"))
                .attributes(response)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }

...
}

사용자의 로그인 데이터를 받으면 구글 로그인인지, 네이버 로그인인지에 따라 데이터 자료형이 다르므로, 같은 자료형으로 변환해주어야 한다.

그 전에 해당 데이터가 구글 로그인으로 얻은 데이터인지, 네이버 로그인으로 얻은 데이터인지 판단이 필요하다.

기존 코드에 네이버인지 판단하는 코드를 추가해 주었다.

  • index.mustache

메인 화면에 네이버 로그인 버튼을 추가한다.

...
						{{^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}}
...

* 정리

API를 사용할 때는 응답값의 구조를 확인하고, 어떤 데이터가 필요한지, 데이터를 어떻게 가공할지, 로직은 어떻게 구성할지 먼저 정해야한다. API 응답값은 API 명세서를 보면 확인 할 수 있다.

* Reference

[블로그] 스프링 시큐리트에서 user 기본값 변경하는 방법

[문서] 스프링 시큐리티의 기본 제공값인 user와 password

참고

도서 - 스프링 부트와 AWS로 혼자 구현하는 웹 서비스

0개의 댓글