[Spring Boot] aLog Project - Spring Security와 OAuth2.0으로 로그인 기능 구현하기 3

김광현·2023년 9월 19일
0

Project - aLog

목록 보기
11/12
post-thumbnail

[Spring Boot] aLog Project - Spring Security와 OAuth2.0으로 로그인 기능 구현하기 2 에 이어서 Spring Security와 OAuth2.0으로 네이버 로그인 기능을 구현합니다. 🏆


💻 네이버 API 등록

[Spring boot] 네이버 로그인 API 연동 과정 글을 읽는 것을 추천드립니다.

먼저 네이버 오픈 API로 이동합니다. 그리고 다음과 같이 각 항목을 채웁니다.

회원이름, 이메일, 프로필 사진은 필수이며 추가 정보는 필요한 경우 선택할 수 있습니다.


구글에서와 마찬가지로 URL을 등록합니다.

서비스 URL은 필수입니다.
Callback URL은 구글에서 등록한 리디렉션 URL과 같은 역할을 합니다.


등록을 완료하면 다음과 같이 ClientID와 ClientSecret이 생성됩니다.



application-oauth.yml

해당 키값들을 application-oauth.yml에 등록합니다.

spring:
  security:
    oauth2:
      client:
        registration:
		...
		  naver:
            client-id: Client ID값
            client-secret: Client Secret값
            redirect-uri: "{baseUrl}/{action}/oauth2/code/{registrationId}"
            authorization_grant_type: authorization_code
            scope: name, email, profile_image
            client-name: Naver

        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

📁 코드 설명

1. user_name_attribute: response
	- 기준이 되는 user_name의 이름을 네이버에서는 response로 해야 합니다.
    - 이유는 네이버의 회원 조회 시 반환되는 JSON 형태 때문입니다.


💻 Spring Security 설정 등록

OAuthAttributes.java

OAuthAttributes.java에 다음과 같이 네이버인지 판단하는 코드와 네이버 생성자를 추가해줍니다.

@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) attributes.get("name"))
                .email((String) attributes.get("email"))
                .picture((String) attributes.get("profile_image"))
                .attributes(attributes)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }
    ...

index.mustache

index.mustache에 네이버 로그인 버튼을 추가합니다.

		...
		{{^userName}}
			<a href="/oauth2/authorization/google" class="btn btn-outline-secondary" role="button">Google Login</a>
			<a href="/oauth2/authorization/naver" class="btn btn-outline-success" role="button">Naver Login</a>
		{{/userName}}
	</div>
</div>
...

📁 코드 설명

1. /oauth2/authorization/naver
	- 네이버 로그인 URL은 application-oauth.yml에 등록한 redirect-uri 값에 맞춰 자동으로 등록됩니다.
    - /oauth2/authorization/ 까지는 고정이고 마지막 Path만 각 소셜 로그인 코드를 사용하면 됩니다.

✔ Spring Security와 OAuth2.0으로 네이버 로그인, 로그아웃, 회원가입, 권한관리 기능을 모두 구현해봤습니다.

profile
🅸nterest 🆂olving 🆃horough 🅹udgment

0개의 댓글