[spring] Naver Session Login

네이버 api 페이지에서 앱 등록

 

application-oauth.properties

#Naver (Naver는 구글처럼 스프링 시큐리티를 공식 지원해주지 않기 때문에 Common-OAuth2Provider에서 해주던 값들도 전부 수동 입력해야한다.)
#registration
spring.security.oauth2.client.registration.naver.client-id=6JlFyUbv0dZqrt3y_Bc5
spring.security.oauth2.client.registration.naver.client-secret=o4IZ_lzzGk
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
# 네이버의 token-uri 속성 추가

#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
#naver API 응답값이 response 안에 username이 들어있다. 시큐리티에서는 하위필드를 명시할 수 없기 때문에 response로 받아서 username을 지정해야함
spring.security.oauth2.client.provider.naver.user-name-attribute=response

 

OAuthAttributes

//OAuth2User에서 반환하는 사용자 정보는 Map이기 때문에 값 하나하나를 변환해야만 한다.
    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();
    }

'개발 > API' 카테고리의 다른 글

[Spring] Google Session Login  (0) 2023.07.31
Kakao Login & Friends API  (0) 2023.03.27