eunja511005 / AutoCoding

0 stars 0 forks source link

OAuth2 카카오 설정 #15

Open eunja511005 opened 1 year ago

eunja511005 commented 1 year ago

Kakao Developers 접속

구글 계정으로 로그인(패스워드는 모바일 메모장에서 확인)

(1) 애플리케이션 추가하기 image

image

(2) 카카오 로그인 활성화 image

image

(3) Redirect URI 등록(/login/oauth2/code/kakao)

- 엄청 중요 : application.properties 파일의 리다이렉트 주소와 동일해야 한다.
- http://localhost:8080/login/oauth2/code/kakao 이걸로 설정 할것

image

image

(4) 가져올 정보 선택 image

image

(5) 잘 적용 되었는지 확인 하기 http://localhost:8080/kauth.kakao.com/oauth/authorize?client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}&response_type=code image

eunja511005 commented 1 year ago

OAtuth2 의존성 추가

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
eunja511005 commented 1 year ago
  1. 의존성 추가

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
  2. application.properties 파일 변경

    ## KAKAO Login
    spring.security.oauth2.client.registration.kakao.client-id=03ef8feea24a093a92736fc82f986513
    spring.security.oauth2.client.registration.kakao.redirect-uri={baseUrl}/{action}/oauth2/code/{registrationId}
    spring.security.oauth2.client.registration.kakao.authorization-grant-type=authorization_code
    spring.security.oauth2.client.registration.kakao.scope=profile_nickname, profile_image, account_email, gender
    spring.security.oauth2.client.registration.kakao.client-name=kakao
    spring.security.oauth2.client.registration.kakao.client-authentication-method=POST
    ## kAKAO Provider
    spring.security.oauth2.client.provider.kakao.authorization-uri= https://kauth.kakao.com/oauth/authorize
    spring.security.oauth2.client.provider.kakao.token-uri=https://kauth.kakao.com/oauth/token
    spring.security.oauth2.client.provider.kakao.user-info-uri=https://kapi.kakao.com/v2/user/me
    spring.security.oauth2.client.provider.kakao.user-name-attribute=id
  3. 컨그파일 설정

    - 카카오나 구글에서 로그인 성공시 호출될 서비스(customOAuth2UserService) 등록
    - 로그인 후 접속 페이지 설정(/main)
    private final CustomOAuth2UserService customOAuth2UserService;
        http.oauth2Login()
                .userInfoEndpoint()
                .userService(customOAuth2UserService)
                .and()
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                            Authentication authentication) throws IOException, ServletException {
                        log.info("userInfo {}", authentication.getPrincipal().toString());
                        log.info("authentication {}", authentication.toString());
                        log.info("authentication Name {}", authentication.getName());
                        response.sendRedirect("/main");
                    }
                });
  4. 로그인 시 호출 서비스 개발(customOAuth2UserService)

    // 카카오나 구글에서 보내준 정보로 유저 있는지 조회해서 있으면 반환하고 없으면 생성 한다.
    // 생성시 기본 유저롤을 부여 한다.
    private UserInfoDTO saveOrUpdate(OAuthAttributes attributes){
        Map<String, Object> map = new HashMap<>();
        map.put("username", attributes.getName()); // 가져온 데이터에 키와 벨류값을 지정
        UserInfoDTO userInfoDTO = testDao.getUser(map);
    
        if(userInfoDTO == null) {
            userInfoDTO = UserInfoDTO.builder().createId("OAuth2")
                                                .isEnable(true)
                                                .username(attributes.getName())
                                                .email(attributes.getEmail())
                                                .picture(attributes.getPicture())
                                                .role("ROLE_USER")
                                                .build();
            userDao.addUser(userInfoDTO);
        }
    
        return userInfoDTO;
    
    }
  5. OAuthAttributes

    public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes){
        // 여기서 네이버와 카카오 등 구분 (ofNaver, ofKakao)
        if("github".equals(registrationId)){
            return ofGithub("id", attributes);
        }
        if("kakao".equals(registrationId)){
            return ofKakao("id", attributes);
        }
        if("google".equals(registrationId)){
            return ofGoogle(userNameAttributeName, attributes);
        }
        return null;
    }
    private static OAuthAttributes ofKakao(String userNameAttributeName, Map<String, Object> attributes) {
        Map<String,Object> response = (Map<String, Object>)attributes.get("kakao_account");
        Map<String, Object> profile = (Map<String, Object>) response.get("profile");
        return OAuthAttributes.builder()
                .name((String)profile.get("nickname"))
                .email((String)response.get("email"))
                .picture((String)profile.get("thumbnail_image_url"))
                .attributes(attributes)
                .nameAttributeKey(userNameAttributeName)
                .build();
    }
  6. 확인 http://localhost:8080/oauth2/authorization/kakao image

eunja511005 commented 1 year ago

화면에 카카오톡 버튼 추가(중요 : /oauth2/authorization/kakao)

<div class="container px-5 mb-3">
    <div class="row justify-content-center">
        <a href="/oauth2/authorization/kakao"><img src="https://developers.kakao.com/tool/resource/static/img/button/login/full/ko/kakao_login_medium_narrow.png"></a>
    </div>
</div>