티스토리 뷰

OAuth

5. 구글 로그인 OAuth 기능 구현 (SDK used)

알 수 없는 사용자 2019. 7. 24. 01:59

 앞서 페이스북 로그인을 사용해보았으니 구글 로그인도 사용해보자.

 

1.  Google Cloud Platform에서 project 생성

- 좌측 상단 new project 버튼

 

2. AOuth Client ID 발급

 1) 좌측 메뉴 API & service -> Credentials 

 2) 하단의 web application 클릭

 3) 원하는 name과 Authorized JavaScript origins, Authorized redirect URIs 입력

 - Authorized JavaScript origins : 웹 애플리케이션의 도메인

 - Authorized redirect URIs : redirect 될 uri

 

3. 로그인 페이지 생성 및 초기화

Google Sign-In JavaScript client reference

 

  페이스북과 마찬가지로 src 경로의 js 파일을 불러온다. 이때 src에 파라미터 onload는 해당 js파일을 로드한 후에 실행할 함수를 호출해준다. 밑의 예제는 init 함수를 호출해주는 것이다. 그 후 auth2에 관한 기능을 로드한 후 뒤의 함수가 호출된다.

후에 client_id를 초기화 하면 리턴 값으로 GoogleAuth 객체가 반환된다. (gauth 변수에 담아둠)

GoogleAuth 객체에서는 연결에 대한 상태를 알 수 있고, 첫 번째 콜백 함수는 성공 시, 두 번째 콜백 함수는 에러시 작동하게 된다.

<!DOCTYPE html>
<html>
    <body>
    	<script>
            function init() {
                gapi.load('auth2', function() { 
                    var gauth = gapi.auth2.init({
                        client_id: 'CLIENT_ID.apps.googleusercontent.com'
                    });
                    
                    gauth.then(function(){
                        console.log('init success');
                    }, function(){
                        console.error('init fail');
                    })
                });
            }
        </script>
        <script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
    </body>
</html>

 

 

4. 로그인 상태 체크

 또한 위에서 생성된 GoogleAuth 객체에서 로그인 체크도 가능하다.

우선 로그인 버튼을 추가하고, 로그인 상태에 따른 버튼에 변화를 준다.

<input type="button" value="checking....." id="authBtn" onclick="
  if(this.value === 'Login') {

  } else {

  }
"> 
gauth.then(function(){
  console.log('init success');
    var isLogined = gauth.isSignedIn.get();
    if(isLogined) {
    	document.querySelector('#authBtn').value = 'Logout';
    } else {
    	document.querySelector('#authBtn').value = 'Login';
    }
  }, function(){
	console.error('init fail');
});

 

5. 로그인 이벤트 추가

이제 로그인을 위한 google api를 버튼 이벤트를 통해 호출하면 된다.

하지만 api호출을 위해서는 GoogleAuth가 필요하게 되는데, 물론 init함수를 통해 생성된 GoogleAuth 객체를 전역변수로 사용할 수도 있지만, 더욱 세련된 방법으로 gapi.auth2.getAuthInstance()을 사용하면 된다.

var gauth = gapi.auth2.getAuthInstance();

  if(this.value === 'Login') {
    gauth.signIn().then(function(){
    	alert('Logined');
    });
  } else {
    gauth.signOut().then(function(){
    alert('Logouted');
    });
  }

이때 then함수는 로그인이나 로그아웃과정이 끝난 후에 호출되는 함수이다.

 

6. scope 설정 및 정보 출력

* Google SignIn Scope 설정

 구글에서의 scope는 다음과 같이 init과정에서 설정할 수 있다.

var gauth = gapi.auth2.init({
  client_id: 'CLIENT_ID.apps.googleusercontent.com',
  scope: 'profile'
});

또한 사용자의 정보는 GoogleAuth 객체의 currentUser을 통해서 구할 수 있다.

gauth.signIn().then(function(response){
  alert('Logined');
  alert(gauth.currentUser.get().getBasicProfile().getEmail());
  location.reload();
});

 

 

지금까지는 클라이언트 사이드에서 서버사이드(백엔드)를 전혀 이용하지 않고 SDK를 사용했다. 하지만 이 방법은 보안 쪽으로 문제가 생길 확률이 높기 때문에 서버사이드를 이용하여 구현하는 게 좋다.

 

백엔드를 이용한 방법을 요약하자면 다음과 같다.

사용자가 버튼을 눌러 요청하는 작업까지는 동일하다. 하지만 access token을 바로 사용자에게 넘기는 것이 아니라, authorization code를 먼저 넘긴다. 그 후 먼저 백엔드(Client)에서 authorization code를 기록하고, 백엔드에서 Resource Server로 직접 통신하여 자신의 client id와 client secret과 authorization code를 보내며 access token을 요청한다. 이후 Resource Server는 3가지 값을 비교하여 일치 여부를 판단한 후 저장하고 있던 authorization code를 삭제 후 access token을 전송한다. 이때 authorization code를 삭제하는 이유는 재접속을 방지하기 위해서다. 결국, Client와 Resource Server가 같은 access token을 저장하게 된다.

이 방법이 더 안전한 이유는 인터넷 브라우저를 통해 사용자 정보를 교환한다는 자체가 매우 위험한 상황이다. 때문에 서버대 서버로 직접 통신하기 때문인 것이다. 

 

하나 더 부가적으로 말하면, 토큰의 만료시간이 다 되어 소멸되었을 때, refresh token을 사용하면 된다. refresh token은 access token과 같이 발급되는데 만약 access token이 만료된다면, refresh token을 이용하여 access tokend을 재발급 받을 수 있다.

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함