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 파일로 변경하니 정상적으로 됨, 확인해봐야 하는 문제

+ Recent posts