본문 바로가기
개발/자바스크립트

<자바스크립트 활용> Federated Indentity, 웹사이트에 페이스 북 아이디로 로그인 구현하기(3편)

by 동국대 ICT 2021. 1. 23.

지난 포스팅에서 우리가 만든 웹 사이트의 개인 정보에 대해 말했습니다.

 

이는 개인 정보 특성상 악용이 가능하기에 보안상 중요한 위치에 있다고 생각됩니다.

 

그리고 이를 보안적으로 보완하고 개발의 부담을 덜기 위해 페이스 북 로그인 기능이 필요하다고 생각됩니다.

 

보다 자세한 내용과 작동원리는 이전 포스팅 참고하시면 이해에 도움 될 것 같습니다!

 

이전에 사용했던 용어를 계속 이어서 사용할 것이기 때문에 완전히 이해하고 싶으신 분들은 꼭 보셨으면 좋겠습니다!

 

donggukice.tistory.com/13

두 번쩨 포스팅은 구글 API를 사용하기 위한 기본 셋팅들에 포스팅했습니다.

 

이 내용을 이번 포스팅을 따라오기 위한 필수적인 내용이니 참고하셔야 해요!!

 

donggukice.tistory.com/14

 

페이스 북

<코드 찾기>

페이스 북 API, SDK 를 사용하기 위한 코드를 어디서 찾아볼 수 있는지 말씀드리겠습니다.

 

우선 저번과 같이 FACEBOOK DEVELOPERS에 접속해줍니다.

 

developers.facebook.com/

 

Facebook for Developers

Facebook for Developers와 사용자를 연결할 수 있는 코드 인공 지능, 비즈니스 도구, 게임, 오픈 소스, 게시, 소셜 하드웨어, 소셜 통합, 가상 현실 등 다양한 주제를 둘러보세요. Facebook의 글로벌 개발

developers.facebook.com

 

페이스북 DEVEOLPER

그 후 상단에 문서를 클릭하여 줍니다.

 

번역하지 않으신 분들은 DOCUMENTS입니다.

 

 

 

페이스북 로그인

그러면 페이스 북에서 사용가능한 많은 API들이 나오는데요.

 

이 중 저희는 페이스북 로그인 기능을 사용할 것이기 때문에 비즈니스 도구 > 페이스북 로그인 으로 들어가줍니다.

 

그렇게 내려가다 보면 전체 코드 예시를 볼 수 있을 것입니다

 

이 부분이 저희가 사용해야 할 부분입니다.

 

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>

  function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
    console.log('statusChangeCallback');
    console.log(response);                   // The current login status of the person.
    if (response.status === 'connected') {   // Logged into your webpage and Facebook.
      testAPI();  
    } else {                                 // Not logged into your webpage or we are unable to tell.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this webpage.';
    }
  }


  function checkLoginState() {               // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) {   // See the onlogin handler
      statusChangeCallback(response);
    });
  }


  window.fbAsyncInit = function() {
    FB.init({
      appId      : '{app-id}',
      cookie     : true,                     // Enable cookies to allow the server to access the session.
      xfbml      : true,                     // Parse social plugins on this webpage.
      version    : '{api-version}'           // Use this Graph API version for this call.
    });


    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
      statusChangeCallback(response);        // Returns the login status.
    });
  };
 
  function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }

</script>


<!-- The JS SDK Login Button -->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
</body>
</html>

 

자바스크립트를 사용하실 줄 아시는 분들이라면 코드 한 번씩 이해하도록 읽어보는 것도 좋을 것 같습니다.

 

 

개발자

<코드 추출하기>

 

이 코드 중 저희가 웹 사이트 코드에 가지고와야 할 코드들이 있습니다.

 

그 부분의 코드들에 대하여 설명드리겠습니다.

 

,SDK 로딩 : HEAD에 SCRIPT 태그 걸어서 해준다!>

 

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
</body>

 

위의 javascript 코드를 복사하여 웹 사이트의 head 태그 안에 넣어주도록 합시다.

 

 

 

<SDK 설정 : HEAD안에 SDK로딩 윗부분>

 

  window.fbAsyncInit = function() {
    FB.init({
      appId      : '{app-id}',
      cookie     : true,                     // Enable cookies to allow the server to access the session.
      xfbml      : true,                     // Parse social plugins on this webpage.
      version    : '{api-version}'           // Use this Graph API version for this call.
    });


    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
      statusChangeCallback(response);        // Returns the login status.
    });
  };

 

위의 javascript 코드를 복사하여 웹 사이트의 head 태그 안에 넣어주도록 합시다.

 

너무 디테일일 수도 있는데 저는 SDK 로딩 코드의 윗 부분에 배치해주었습니다.

 

간단하게 코드 내용에 대해 설명해드리자면

fbAsynInit : 초기화 끝난 다음에 fbAsynInit변수를 window에 지정하고 함수형태로 만들라는 뜻. ({}은 객체라는 뜻)
SDK 다운로드 끝나면 함수 실행하도록.
fb : facebook 약자
객체안에 있기에 메소드의 한 종류이다.

- 수정 내용 -

 

그리고 본인의 웹 사이트에 맞게 코드 상 수정해주어야 할 부분이 있습니다.

appID : client ID 값 -> APP ID를 사용하면 된다. 복붙해라.
version : 버전 -> 페이스북 API CHANGE LOG(바뀐 기록) 검색 -> 제일 위에 버전 나와있음. 

 

로그인 되었는지 확인하는 코드 입니다.

 

FB.getLoginStatus : 로그인 상태에 대한 코드

 

  function checkLoginState() {               // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) {   // See the onlogin handler
      statusChangeCallback(response);
    });
  }

 

자바스크립트를 다루실 줄 아시는 분이라면 이 코드를 콘솔화면창에 띄우도록 console.log 를 사용하시면

 

크롬 > 검사 > console 에서 제대로 동작하고 있는지 확인하실 수 있으실 겁니다!!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

댓글