Spring/Skill

[spring] OAuth2 구글 인증하기

31daylee 2024. 2. 7. 17:32
728x90

 

 

구축 환경 💻
Spring boot + JSP 

 

 

📌 Google 공식 문서


 

웹 서버 애플리케이션용 OAuth 2.0 사용  |  Authorization  |  Google for Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. 의견 보내기 웹 서버 애플리케이션용 OAuth 2.0 사용 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 이

developers.google.com

 

 

 

📌 Google API 서비스 등록하기


 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

 

 

 

왼쪽 상단바 클릭 - [API 및 서비스] - [OAuth 동의 화면]

 

 

[외부] - [만들기] 클릭 

 

 

필수 입력 기입 후 [저장 후 계속] 클릭

 

 

[범위] / [테스트 사용자] 별다른 클릭 및 기입 없이 진행
> 프로젝트 생성은 완료 

 

 

 

 

[사용자 인증 정보] - [+ 사용자 인증 정보 만들기] - [OAuth 클라이언트 ID]

 

 

필요에 맞게 선택 

 

 

 

승인된 자바스크립트 원본/ 승인된 리디렉션 URI 모두 기입 후 [만들기] 진행 

 

[클라이언트 ID] / [클라이언트 보안 비밀번호]는 추후에 사용될 예정이니, 따로 메모장에 기록해두기

 

 

 

 

 

 

📌 프론트 설정하기


 

google login 아이콘 클릭 시 해당 페이지로 redirect 되는 리소스에 접근 가능한 부분은 프론트에서 진행한다.

<a href ="https://accounts.google.com/o/oauth2/auth?
client_id={클라이언트 ID}
&redirect_uri={리디렉션 URI}
&response_type=code
&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile">

 

해당하는 부분의 값을 넣어주었다. 그리고 아래와 같이 리다이렉트 된 것을 확인할 수 있다

 

 

 

 

📌 서버 설정하기 


import java.util.Properties;

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;

//json 형식에 코딩 컨벤션의 스네이크 케이스를 카멜 노테이션으로 변경하기 
@Data
@JsonNaming(value=PropertyNamingStrategies.SnakeCaseStrategy.class)
public class OAuthToken {
	
	private String accessToken;
	private String tokenType;
	private String refreshToken;
	private Integer expiresIn;
	private String scope;
	private Integer refreshTokenExpiresIn;

}

 

package com.tenco.bank.dto.oauth.google;

import lombok.Data;

@Data
public class GoogleProfile {

    private String id;
    private String name;
    private String givenName;
    private String familyName;
    private String picture;
    private String locale;

}

 

@GetMapping("/google-callback")
public String googleCallback(@RequestParam("code") String accessCode) {

    RestTemplate rt1 = new RestTemplate();
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", accessCode);
    params.add("client_id", "132467987.com");
    params.add("client_secret", "1234654");
    params.add("redirect_uri", "http://localhost:80/user/google-callback");
    params.add("grant_type", "authorization_code");


    ResponseEntity<OAuthToken> response1 =  rt1.postForEntity("https://oauth2.googleapis.com/token",
            params, OAuthToken.class);


    // 액세스 토큰 -> 사용자 정보
    RestTemplate rt2 = new RestTemplate();
    HttpHeaders headers2 = new HttpHeaders();

    headers2.add("Authorization","Bearer " +response1.getBody().getAccessToken()) ;
    HttpEntity<MultiValueMap<String, String>> googleInfo = new HttpEntity<>(headers2);
    ResponseEntity<GoogleProfile> response2 =  rt2.exchange("https://www.googleapis.com/userinfo/v2/me",
                                                HttpMethod.GET, googleInfo, GoogleProfile.class);

    System.out.println(response2.getBody());
    GoogleProfile googleProfile = response2.getBody();
    System.out.println(response2.getBody());
    SignUpFormDto dto = SignUpFormDto.builder()
                                    .username("Google_"+ googleProfile.getName())
                                    .fullname("Google")
                                    .password("1111")
                                    .build();

    User oldUser =  userService.readUserByUsername(dto.getUsername());
    if(oldUser == null) {
        userService.createUser(dto);
        oldUser = new User();
        oldUser.setUsername(dto.getUsername());
        oldUser.setFullname(dto.getFullname());
    }
    oldUser.setPassword(null); 

    httpSession.setAttribute(Define.PRINCIPAL, oldUser);

    return "redirect:/account/list";

}

 

 

토큰 요청 URI : https://oauth2.googleapis.com/token 
> Method: POST

사용자 정보 요청 URI : https://www.googleapis.com/userinfo/v2/me
> Method: GET

 

 

 

 

 

 

 

 

 

 


<관련 자료>

Kakao 소셜 로그인 하러 가기 

https://31daylee.tistory.com/51

 

[spring] OAuth2 카카오 인증하기 + kakao 이메일 인증 권한 받는 법

구축 환경 💻 Springboot + JSP 📌카카오 인증 구조 이해하기 💡 관련 개념 이해하기 REST API를 이용한 인증 처리는 어떻게 되는가? Service Server 는 Redirect_URI/Client_ID/Response_type 을 인증서버(Kakao Auth Ser

31daylee.tistory.com

 

728x90