Authentication

Please note: We are in the process of deprecating the offline_access permission, so if you are building a new application you shouldn't use this permission. Instead please check the Deprecation of Offline Access Permission document which explains how to start using access tokens that are valid for up to 60 days

Facebook Platform uses the OAuth 2.0 protocol (required as of October 1, 2011) for authentication and authorization. We support a number of different OAuth flows that you can use within your Website, mobile and desktop apps.

This document outlines that different mechanisms Facebook Platform uses to support each of these flows. The examples in this document use PHP for server-side programming and HTML/JavaScript for client-side code. These examples are very straightforward and easily translatable to other languages.

User Login

Facebook Platform supports two different OAuth 2.0 flows for user login: server-side (known as the authentication code flow in the specification) and client-side (known as the implicit flow). The server-side flow is used whenever you need to call the Graph API from your web server. The client-side flow is used when you need to make calls to the Graph API from a client, such as JavaScript running in a Web browser or from a native mobile or desktop app.

Regardless of the flow you utilize, our implementation of the OAuth 2.0 involves three different steps: user authentication, app authorization and app authentication. User authentication ensures that the user is who they say they are. App authorization ensures that the user knows exactly what data and capabilities they are providing to your app. App authentication ensures that the user is giving their information to your app and not someone else. Once these steps are complete, your app is issued an user access token that enables you to access the user's information and take actions on their behalf.

Server-side Flow

User authentication and app authorization are handled at the same time by redirecting the user to our OAuth Dialog. When invoking this dialog, you must pass in your app id that is generated when you create your application in our Developer App (the client_id parameter) and the URL that the user's browser will be redirected back to once app authorization is completed (the redirect_uri parameter). The redirect_uri must be in the path of the Site URL you specify in Website section of the Summary tab in the Developer App. If it is the root of the domain, it should end with a trailing slash. Note, your redirect_uri can not be a redirector.

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL

See the Alternate Redirect URIs section below for more information.

If the user is already logged in, we validate the login cookie that we have stored on the user's browser, authenticating the user. If the user is not logged in, they are prompted to enter their credentials:

Auth Login

Once we have successfully authenticated the user, the OAuth Dialog will prompt the user to authorize the app:

Auth Authz

By default, the user is asked to authorize the app to access basic information that is available publicly or by default on Facebook. If your app needs more than this basic information to function, you must request specific permissions from the user. This is accomplished by adding a scope parameter to the OAuth Dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to user's email address and their news feed:

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream

This results in the following dialog being presented to the user after they are authenticated:

Auth Perms

A full list of permissions is available in our permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; so we recommend that you only request the permissions you absolutely need for your app.

If the user presses Don't Allow, your app is not authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with the following error information:

http://YOUR_URL?error_reason=user_denied&
     error=access_denied&error_description=The+user+denied+your+request.

If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with an authorization code:

http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER

With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.

In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint - along with the exact same redirect_uri used above - at https://graph.facebook.com/oauth/access_token. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will distribute (you should use the client-side flow for these scenarios).

https://graph.facebook.com/oauth/access_token?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
     client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

If your app is successfully authenticated and the authorization code from the user is valid, the authorization server will return the access token:

Auth Token

In addition to the access token (the access_token parameter), the response contains the number of seconds until the token expires (the expires parameter). Once the token expires, you will need to re-run the steps above to generate a new code and access_token, although if the user has already authorized your app, they will not be prompted to do so again. If your app needs an access token with an infinite expiry time (perhaps to take actions on the user's behalf after they are not using your app), you can request the offline_access permission.

If there is an issue authenticating your app, the authorization server will issue an HTTP 400 and return the error in the body of the response:

{
   "error": {
      "type": "OAuthException",
      "message": "Error validating verification code."
   }
}

The diagram below illustrates the HTTP calls made through the server-side flow:

serversideflow.png

The following PHP example demonstrates the server-side flow with CSRF protection in one self-contained example:

 <?php 

   $app_id = "YOUR_APP_ID";
   $app_secret = "YOUR_APP_SECRET";
   $my_url = "YOUR_URL";

   session_start();
   $code = $_REQUEST["code"];

   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
     $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'];

     echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }

   if($_REQUEST['state'] == $_SESSION['state']) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = @file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

     $graph_url = "https://graph.facebook.com/me?access_token=" 
       . $params['access_token'];

     $user = json_decode(file_get_contents($graph_url));
     echo("Hello " . $user->name);
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }

 ?>

Client-side Flow

The client-side flow also uses the OAuth Dialog for user authentication and app authorization. The only difference is that you must specify the response_type parameter with a value of token:

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&response_type=token

As with the server-side flow, you can also request additional permissions using the scope parameter:

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream&
     response_type=token

Once the user is authenticated and authorizes your application, the browser will be redirected to redirect_uri but rather than being passed a authorization code (via the code parameter) as in the server-side flow, the redirect_uri is passed the access token in a URI fragment (#access_token):

http://YOUR_URL#access_token=166942940015970%7C2.sa0&expires_in=64090

Because the access token is passed in an URI fragment, only client-side code (such as JavaScript executing in the browser or desktop code hosting a web control) can retrieve the token. App authentication is handled by verifying that the redirect_uri is in the same path as the Site URL configured in the Developer App. See the Alternate Redirect URIs section below for more information.

The diagram below illustrates the HTTP calls made through the client-side flow:

clientsideflow.png

The following HTML/JavasScript example demonstrates the client-side flow in one self-contained example:

 <html> 
   <head> 
     <title>Client Flow Example</title> 
   </head> 
   <body> 
   <script> 
     function displayUser(user) {
       var userName = document.getElementById('userName');
       var greetingText = document.createTextNode('Greetings, '
         + user.name + '.');
   userName.appendChild(greetingText);
     }

     var appID = "YOUR_APP_ID";
     if (window.location.hash.length == 0) {
       var path = 'https://www.facebook.com/dialog/oauth?';
   var queryParams = ['client_id=' + appID,
     'redirect_uri=' + window.location,
     'response_type=token'];
   var query = queryParams.join('&');
   var url = path + query;
   window.open(url);
     } else {
       var accessToken = window.location.hash.substring(1);
       var path = "https://graph.facebook.com/me?";
   var queryParams = [accessToken, 'callback=displayUser'];
   var query = queryParams.join('&');
   var url = path + query;

   // use jsonp to call the graph
       var script = document.createElement('script');
       script.src = url;
       document.body.appendChild(script);        
     }
   </script> 
   <p id="userName"></p> 
   </body> 
  </html>

Using the Access Token

With a valid access token you can invoke the Graph API by appending the access_token parameter to Graph API (and Legacy REST API) requests:

 https://graph.facebook.com/me?access_token=ACCESS_TOKEN 

If the user changes their password, the access token expires or the user deauthorizes your app in the App Dashboard, the Graph API will issue an HTTP 400 and return the error in the body of the response:

{
   "error": {
      "type": "OAuthException",
      "message": "Error validating access token."
   }
}  

Your app can request a new access token by re-running the appropriate flow if this error occurs.

App Deauthorization

When a user of your app removes it in the App Dashboard or blocks the app in the News Feed, your app can be notified by specifying a Deauthorize Callback URL in the Developer App. During app removal we will send an HTTP POST request containing a single parameter, signed_request, which contains the user id (UID) of the user that just removed your app. You will not receive an user access token in this request and all existing user access tokens will be automatically expired.

Alternate Redirect URIs

When redirect_uris are specified in the authentication flows, the user is normally redirected to a path under the Site URL that you specify in the Basic Info section on the Summary tab in the Developer App. However, you can override this behavior and redirect to one or more other related or sub-domains by specifying each domain name in the App Domain field in the Basic Info section of the Summary Tab in the Developer App:

App Domains

 

Specifying additional App Domains for your app is useful for redirecting users to other servers for geographic distribution of load, for example.

However, please note that your redirect_uri can not be a redirector.

Logout

You can log a user out of their Facebook session by directing them to the following URL:

https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN

YOUR_URL must be a URL in your site domain, as defined in the Developer App.

App Login

In addition to User Login, Facebook Platform support App Login using the OAuth 2.0 Client Credential flow. App Login allows you to take various administrative actions for your app, such as retrieving Insights data or approving Requests. Graph API calls that require an app access token are clearly denoted in the API reference.

You can obtain the app access token from the Graph API token endpoint at https://graph.facebook.com/oauth/access_token by specifying your app id, app secret and client_credentials in the grant_type parameter. Both the app id and app secret are generated when your app is created in the Developer App.

https://graph.facebook.com/oauth/access_token?
     client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
     grant_type=client_credentials

Sending an HTTP GET request to the above URL will return an access_token in the body of the response:

App Token

You then use this access token when calling app specific parts of the Graph API (such as App Insights):

https://graph.facebook.com/YOUR_APP_ID/insights?
     access_token=TOKEN_FROM_ABOVE

Page Login

Facebook Pages follow a slightly different flow from user and app login. Every Page has one or more administrator which can perform privileged operations on the Page. In order for your app to perform these privileged operations, the user must grant your app the manage_pages permission:

https://www.facebook.com/dialog/oauth?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=manage_pages&
     response_type=token

Manage Pages

Once an administrator has granted your app this permission, you can then access the account connection of the User Graph API:

https://graph.facebook.com/me/accounts?access_token=TOKEN_FROM_ABOVE

This connection returns a list of all the Pages the user administers including Page specific access token for each Page:

Page Tokens

You can use the access token returned for a given Page to perform administrative actions on behalf of the user on that Page.

App Types

Facebook Platform provides a number of ways to use the above OAuth flows in different app types, including Websites, Apps on Facebook.com, Mobile and Desktop Apps.

Websites

Our Website Getting Started Guide provides an overview of adding user login to your Website using our JavaScript SDK and Login Social Plugin.

Apps on Facebook.com

Our Apps on Facebook.com Getting Started Guide provides details on how to handle user login when integrating your app into our core experience on Facebook.

Mobile Apps

The Mobile App Getting Started Guide highlights how to use our mobile SDKs and the mobile support in the OAuth Dialog to perform user login on mobile devices.

Desktop Apps

Our OAuth 2.0 implementation does not include explicit desktop app support. However, if your desktop app can embed a web browser (most desktop frameworks such as .NET, AIR and Cocoa support embedding browsers), you can use the client-side flow with one modification: a specific redirect_uri. Rather than requiring desktop apps to host a web server and populate the Site URL in the Developer App, we provide a specific URL you can use with desktop apps: https://www.facebook.com/connect/login_success.html.

  • Embed a web browser and load the OAuth Dialog (https://www.facebook.com/dialog/oauth) using the client-side flow (i.e. response_type=token):
https://www.facebook.com/dialog/oauth?
    client_id=YOUR_APP_ID&
    redirect_uri=https://www.facebook.com/connect/login_success.html
  • After the user authorizes your app, we redirect the user back to the redirect_uri with the access token in the URI fragment:
https://www.facebook.com/connect/login_success.html#access_token=...
  • Detect this redirect and then read the access token out of the URI using whatever mechanisms provided by your framework of choice.

Security Considerations

Cross Site Request Forgery (CSRF)

Cross site request forgery is an attack in which a trusted (authenticated and authorized) user unknowingly performs an action on website. To prevent this attack, you should pass an identifier in the state parameter, and then validate the state parameter matches on the response. We strongly recommend that any app implementing Facebook user login implement CSRF protection using this mechanism.

Redirect_URI

Please be aware that you can not specify a redirector for the redirect_uri. Visit the OAuth 2.0 section 10.15 for further details.

转载于:https://my.oschina.net/leeming/blog/42725

Neuromuscular Password-Based User Authentication(神经肌肉密码用户认证)是一种基于生物特征的身份验证方法,它利用了人体神经肌肉系统的特性来验证用户的身份。该方法通过监测用户在输入密码时的神经肌肉反应,来判断是否为合法用户。 具体来说,Neuromuscular Password-Based User Authentication使用了肌电图(EMG)信号和脑电图(EEG)信号来获取用户的生物特征信息。当用户输入密码时,系统会记录下相应的神经肌肉反应,并与预先录制的合法用户的反应进行比对。如果两者匹配,则认证成功。 这种身份验证方法具有一定的优势,例如: 1. 生物特征唯一性:每个人的神经肌肉反应都是独特的,因此可以有效地区分不同的用户。 2. 难以伪造:与传统的密码认证相比,神经肌肉反应很难被模仿或伪造。 3. 高安全性:由于使用了生物特征信息,该方法可以提供更高的安全性,减少了密码泄露和盗用的风险。 然而,Neuromuscular Password-Based User Authentication也存在一些挑战和限制: 1. 设备依赖性:该方法需要使用专门的设备来采集和分析神经肌肉反应,增加了实施的成本和复杂性。 2. 用户接受度:由于需要用户配合进行生物特征采集,可能会引起一些用户的隐私和安全担忧,降低用户的接受度。 3. 可靠性和误识别率:神经肌肉反应受到多种因素的影响,如情绪、疲劳等,可能导致认证的准确性和可靠性有所下降。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值