Tech Collection

[Login] Google Login API - JavaScript, JSP 본문

Build/Note

[Login] Google Login API - JavaScript, JSP

eee_269 2020. 12. 24. 03:50
728x90
반응형

1. Google Cloud Platform 로그인 후 접속

https://console.developers.google.com/projectselector2/apis/dashboard?hl=ko&organizationId=0&supportedpurview=project

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

2. 프로젝트 만들기

왼쪽 위

프로젝트 선택

 

새 프로젝트 누르고 프로젝트 생성

 

3. 사용자 인증 정보 만들기

API키, OAuth 클라이언트 ID 두 가지 모두 발급하기

 

4. OAuth 클라이언트 ID

웹 애플리케이션 선택 후 이름 설정하기

URI > URI 추가 후 프로젝트 실행주소 앞부분 입력

 

저장 후 생성되는 클라이언트 ID, 클라이언트 보안 비밀 기억해두기!

 

5. JavaScript 생성하기

https://developers.google.com/identity/sign-in/web/reference

 

Google Sign-In JavaScript client reference

This reference describes the JavaScript client methods and attributes you will use to implement Google Sign-In in your web applications. If you encounter any issue using the library, please report it to our GitHub repository. Auth Setup Load the Google API

developers.google.com

head 태그사이에 넣기

...
<meta name="google-signin-client_id" content="클라이언트ID">
<script src="https://apis.google.com/js/platform.js" async defer></script>
...

방금 발급 받은 클라이언트 ID 를 content에 넣기

body 태그 안에 구글 로그인 버튼 넣기

<!-- 구글 로그인 버튼 노출 영역 -->
<div class="g-signin2" onclick='onSignIn()'></div>
<!-- //구글 로그인 버튼 노출 영역 -->

body 태그 밑에 script 생성

<script type="text/javascript">
    function onSignIn() {
        // 페이지 로딩 시 자동으로 값들고오지 않게 끔 설정
        var profile = gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile();
          id = profile.getId();
          username = profile.getName();
          img = profile.getImageUrl();
          email = profile.getEmail();
          alert('로그인 완료');
          
          post_to_url( "최종 로그인 할 URL",
                    {'id': id, 'username': username, 'email': email, 'img': img})
    }
    function post_to_url(path, params, method='post') {
          const form = document.createElement('form');
          form.method = method;
          form.action = path;
          
          for(const key in params) {
              if(params.hasOwnProperty(key)) {
                  const hiddenField = document.createElement('input');
                  hiddenField.type = 'hidden';
                  hiddenField.name = key;
                  hiddenField.value = params[key];
                  form.appendChild(hiddenField);
                }
              }
              document.body.appendChild(form);
              form.submit();
        }

</script>

onSignIn 함수의 post_to_url 의 첫번째 파라미터는 최종적으로 로그인을 수행하는(정보를 넘길) 페이지 주소 입력

 

 

로그인 버튼

로그인 버튼 클릭 후 로그인되면 성공!

728x90
반응형