Facebook login using OAuth 2.0

后端 未结 4 1029
Happy的楠姐
Happy的楠姐 2021-01-15 10:20
  1. I want people to log in to my site with their Facebook accounts.
  2. I need to pull some info from their Facebook profile and add it to my site\'s database
4条回答
  •  心在旅途
    2021-01-15 11:12

    Exchange the code for a user access token

    Once the user has authorized your app, you should make a server side request to exchange the code returned above for a user access token.

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

    The client_secret parameter must be the App Secret as shows in your app's settings. The body of the response to this request will be a url encoded string of the form:

    access_token=USER_ACESS_TOKEN&expires=NUMBER_OF_SECONDS_UNTIL_TOKEN_EXPIRES
    

    You should parse this string and use the access_token value to make requests to the Graph API. You should also persist the access token in your database in order to make further requests to the API without having to re-authenticate the user.

    Once the access token expiry time is reached, the token will become invalid and can no longer be used in requests to the API. To obtain a new user access token, you must pass the user through this flow again. However, if the user has not deauthorized your app and you're asking for no permissions beyond those which the user has already granted your application, then no dialog will be displayed and the user will be transparently redirected to your redirect_uri with a fresh code which can be exchanged for a fresh user access token.

    If there is an issue exchanging the code for a user access token, the authorization server will issue an HTTP 400 and return the error as a JSON object in the body of the response:

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

    For further reference checkout http://developers.facebook.com/docs/authentication/server-side/

    Making requests to the Graph API

    With a valid user access token, you can make requests to read and write data from the Graph API. A common first request would be to get the basic information (including the id and name) of the user who just authenticated your app:

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

提交回复
热议问题