Facebook application development authentication and authorization process example

Some time ago due to work needs, authorized login to fb and obtained the corresponding access token (access_token), that is, authorized login! Researched the issues related to facebook application development, read the official API documentation, and organized the information to share with you. This article is about the sorting of information on Facebook authentication and authorization, combined with my own actual test to summarize the article, I hope it will be helpful to everyone!

The Facebook platform uses the OAuth2 protocol as the authentication and authorization protocol. It has two authentication processes, Server-Sizde Flow and Client-Side Flow. These authentication processes can be used to develop website applications, mobile Application or desktop application.

This document uses the example of user login and outlines the two authentication and authorization processes supported by facebook. In this example, the server uses python-flask and the client uses HTML/JavaScript (JS SDK), but they can be easily converted to Other programming languages. Two authentication and authorization processes, server-side and client-side, the server-side process is that the Web server calls Graph API to complete authentication and authorization, and the client-side process is that the client calls Graph API to complete the authentication And authorization, such as using javascript running on the browser or local mobile applications or desktop applications.

Regardless of the process used, it has several steps: user authentication, application authorization, and application authentication. User authentication ensures that the user is correct, application authorization ensures that the user knows exactly what data and capabilities he has authorized to the application, and application authentication ensures that the user gives the information to this application instead of other applications. Once the authentication and authorization are completed, the application can use the access token to access the user's information and perform operations on behalf of the user.

Among the reference documents:

https://developers.facebook.com/docs/facebook-login
https://developers.facebook.com/docs/marketing-api/access/

1. Server-side authorization
This example is mainly based on python-flask development as a practical explanation. When all the callback urls need https, the callback test url: https://test/main/home
redirect_uri The callback url needs to be pre-configured in the app In the OAuth Redirect URIs of Facebook Login, you can trust the whitelist! Otherwise, it cannot be authorized normally

  • 1. When the user clicks on an authorization button or login button on the front-end page, it will be redirected to the authorized login page:
https://www.facebook.com/v3.3/dialog/oauth?client_id={
    
    client_id}&redirect_uri={
    
    redirect_uri}&scope={
    
    scope}&response_type=code&state={
    
    state}

Parameter introduction:
client_id: application ID created by facebook
redirect_uri: after the user logs in successfully or fails, the callback (redirect) address, facebook verification brings the cookie information saved in the browser, if the user is already logged in at this time, the authentication is completed. If you are not logged in, return to the following interface. After the user fills in the information, click the login
scope: Permission list, a collection of permissions that need to be authorized to the user, separated by commas, such as: email, read_stream
state: random string, don’t know what to do for the time being use

  • 2. After the login is successful, you will go to the authorization confirmation page. Once confirmed, it will be redirected to the redirect_uri specified path, and the code parameter will be spliced ​​after the url path. The code parameter is very important. Because the access_token needs code as a parameter later, and every time The obtained code can only be used once and it will become invalid immediately!
  • 3. Get the code according to a series of front-end operations, and use it to get access_token in one click:
https://graph.facebook.com/oauth/access_token?client_id={
    
    client_id}&redirect_uri={
    
    redirect_uri}&client_secret={
    
    client_secret}&code={
    
    code}

Parameter introduction:
client_id: application ID
created by facebook client_secret: application key created by facebook
redirect_uri: callback (redirect) address after user login succeeds or fails, facebook authentication brings to the cookie information saved in the browser, if this time The user has logged in, then the authentication is completed. If you are not logged in, return to the following interface, and after the user fills in the information, click the login
code: the code data obtained by the previous authorization login

Instance request result:
  • 1. Get the code
https://www.facebook.com/v3.3/dialog/oauth?client_id=client_id&redirect_uri=https://test/main/home&scope=ads_management,ads_read,email,public_profile,manage_pages,pages_show_list,publish_pages,business_management,pages_manage_cta&response_type=code&state=asaswqdcszq
result:
https://graph.facebook.com/oauth/access_token?client_id=client_id&redirect_uri=https://test/main/home&client_secret=client_secret&code=AQAb9BtXhfQ0OsqTYyLZiuVgPKpMJI9gBRImU_xOwsv26vpXWap5yERv2kB1UgUSOzAoSsJ5w_8hqhlUDVAzeHAh7qlc6O8XrvtqlA5zFpgMLr1M06EXfK0M9T8Y38q3YjO1qmsmWh_BgL87ZKXZELBAWzCBe1MCY6cgbvaQ0kI0jdu7_SVCdRUHFPgZOW7A3RHta0MvQhbb1bhMgch51O7uXf6zIfATv4Tt7AbItKo9qCS5Ory9CozC4l2mqOMPIXtVrRRMy0ZZI75NNO7uycdO23E4plPy8NF8lx_nnadCy_63guD-M-Ush1_qRVJBT2sfnH_fzh9lpdCZ1CX5Rqiq
  • 2. Get the token
https://graph.facebook.com/oauth/access_token?client_id=client_id&redirect_uri=https://test/main/home&client_secret=client_secret&code=AQAb9BtXhfQ0OsqTYyLZiuVgPKpMJI9gBRImU_xOwsv26vpXWap5yERv2kB1UgUSOzAoSsJ5w_8hqhlUDVAzeHAh7qlc6O8XrvtqlA5zFpgMLr1M06EXfK0M9T8Y38q3YjO1qmsmWh_BgL87ZKXZELBAWzCBe1MCY6cgbvaQ0kI0jdu7_SVCdRUHFPgZOW7A3RHta0MvQhbb1bhMgch51O7uXf6zIfATv4Tt7AbItKo9qCS5Ory9CozC4l2mqOMPIXtVrRRMy0ZZI75NNO7uycdO23E4plPy8NF8lx_nnadCy_63guD-M-Ush1_qRVJBT2sfnH_fzh9lpdCZ1CX5Rqiq
result:
{
    
    
    "access_token": "EAAY8lTqahuABAA91OO0mfZB0XZBOkJsKG6GykI2rZBBOEJcE5eBRkzZCtSx0Fry5Ax40EZBj6BdVG0QWhCE1ag7ZBCore5pRX7JbOpXOEjyYg7caAxHLssjajsdjsqmwnhfsxckKSA152266554sDhThh4gVNYAzHQH88bxKmT3xTGPSM",
    "token_type": "bearer"
}
Authorized login

Insert picture description here

2. Client-side authorization
Client-side authorization mainly uses the authorization method of JS sdk for authorization.
This kind of callback url is normally the current page of clicking the Continue with Facebook button. The following method is not recommended. It is more troublesome. If you don’t know, you can also check that a login window will pop up when you click to log in. Copy the above url and find the back of fallback_redirect_uri The url is the authorization callback url, which is actually the url of the current page! !
Login-btn login front-end source code:

<div class="fb-login-button" data-size="large" onlogin="checkLoginState()" data-button-type="continue_with" data-layout="default" data-auto-logout-link="false" data-use-continue-as="false" data-width=""></div>
<script>
  
  function statusChangeCallback(response) {
     
       // Called with the results from FB.getLoginStatus().
    if (response.status === 'connected') {
     
        // Logged into your webpage and Facebook.
      if (response.authResponse) {
     
     
           var access_token =   FB.getAuthResponse()['accessToken']; // get accessToken
           swal({
     
        
              title: "授权登陆中!",   
              text: "请稍后...",  
              showConfirmButton: false 
          });
          // 存储access_token
           $.ajax({
     
     
                url: 'https://test/main/get_access_token',
                method: 'POST',
                data: {
     
     "access_token": access_token
                   },
                success:function(response){
     
     
                    window.location.href = '{
     
     { url_for("main.home") }}'
                }
            })
         } else {
     
     
           console.log('User cancelled login or did not fully authorize.');
         }
    } 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      : '{
     
     { client_id }}',
      cookie     : true,                     // Enable cookies to allow the server to access the session.
      xfbml      : true,                     // Parse social plugins on this webpage.
      version    : 'v7.0',           // 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.
    // });
  };

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

Insert picture description here

Authorized login

Insert picture description here

Guess you like

Origin blog.csdn.net/Lin_Hv/article/details/107681638