TIL wecode 28-2. Google Sign-In

이조은·2020년 9월 5일
0

TIL wecode

목록 보기
26/36

Google Sign-In

Intergrate Google Sign-In

  1. Create authorization credential
  • Google API Console로 이동
  • Create credentials > OAuth cliend ID
  • Web application 어플리케이션 타입을 선택
  • OAuth 2.0 클라이언트의 이름을 짓고 Create 클릭
  1. Load the Google Platform Library
  • Google Sign-In을 웹사이트에 넣기 위해서 Google Platform Library를 꼭 포함시켜야 한다
<script src="https://apis.google.com/js/platform.js" async defer></script>
  1. Specify your app's client ID
  • Google Developers Console에서 내 어플리케이션을 위해 발급된 client ID를 google-signin-client_id메타 요소에 적어준다.
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
  1. Add a Google Sign-In button
  • 아래의 코드를 추가하는 것이 Google Sign-In 버튼을 추가하는 가장 쉬운 방법이다. 이로써 이 버튼은 client가 요청한 scope과 유저의 가입을 위한 텍스트, 로고 등을 갖추게 된다.
<div class="g-signin2" data-onsuccess="onSignIn"></div>

  1. Get profile information
  • 유저로 하여금 구글에 로그인한 후에는 유저의 정보들에 접근할 수 있다. 이를 위해서는 getBasicProfile()을 이용한다.
function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}
  1. Sign out a user
  • user로 하여금 구글에서 로그아웃 하는 절차 없이 나의 어플리케이션을 로그아웃 할 수 있게 하는 방법이 있다. 이 링크를 생성하기 위해 GoogleAuth.signOut()을 호출해 onclick이벤트에 걸어 놓자.
<a href="#" onclick="signOut();">Sign out</a>
<script>
  function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }
</script>

Authenticate with a Backend Server

백엔드 서버와 통신하는 Google Sign-In을 사용하기 위해서는 현재 서버에 로그인한 유저를 확인시켜줄 필요가 있다. 안전하게 하기 위해서는 유저가 성공적으로 로그인한 후에 user의 토큰을 HTTPS를 사용하는 내 서버에 보내주어야 한다. 그러면 서버에서 그 토큰의 무결성을 확인하고 새 계정을 만들기 위해 토큰에 포함된 유저의 정보를 사용할 수 있다.

  1. Send the ID token to your server
  • 유저가 로그인하고 난 후 유저의 ID token을 얻는다
function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;
  ...
}
  • 이 ID token을 HTTPS POST 요청을 통해 내 서버에 보낸다.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
  console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
profile
싱글벙글

0개의 댓글