Facebook OAuth2 for Classic ASP – Step 2

This is the second of a series of two posts to demonstrate implementing OAuth2 Authorization for Facebook in Classic ASP.
(Also see: Facebook OAuth2 for Classic ASP – Step 1)
This ASP is called when Facebook returns a redirect after the FB account owner either grants or denies access.

Here is the ASP source for Step 2:


' Replace with actual values.
AppId = "FACEBOOK-APP-ID"
AppSecret = "FACEBOOK-APP-SECRET"
	
' I'm using ngrok to callback to my web server running on localhost..
'RedirectUri = Server.URLEncode("https://www.your-website.com/fb_finishOAuth2.asp")
RedirectUri = Server.URLEncode("https://abca3bde.ngrok.io/fb_finishOAuth2.asp")


' Get the incoming query parameters.
' If access was denied/canceled, we'll get the following params:
' 
'     error_reason=user_denied 
'     error=access_denied 
'     error_description=The+user+denied+your+request.
'
' If access is granted, we'll get the "state" echoed back to us,
' and we'll also get a "code".

' We'll assume it succeeded..
code = request.querystring("code")
state = request.querystring("state")

' If we wanted, we could verify that the "state" received here is equal to 
' Session("oauth2_state")   

' ------------------------------------
'  Exchanging Code for an Access Token
' ------------------------------------
'  To get an access token, make an HTTP GET request to the following OAuth endpoint:

'  GET https://graph.facebook.com/v2.8/oauth/access_token?
'     client_id={app-id}
'     &redirect_uri={redirect-uri}
'     &client_secret={app-secret}
'     &code={code-parameter}

set http = Server.CreateObject("Chilkat_9_5_0.Http")

success = http.UnlockComponent("Anything for 30-day trial")
If (success <> 1) Then
    Response.Write "<pre>" & Server.HTMLEncode( http.LastErrorText) & "</pre>"
	Response.End 
End If

set sbUrl = Server.CreateObject("Chilkat_9_5_0.StringBuilder")
success = sbUrl.Append("https://graph.facebook.com/v2.8/oauth/access_token?client_id={app-id}&redirect_uri={redirect-uri}&client_secret={app-secret}&code={code-parameter}")
replaceCount = sbUrl.Replace("{app-id}",AppId)
replaceCount = sbUrl.Replace("{redirect-uri}",RedirectUri)
replaceCount = sbUrl.Replace("{app-secret}",AppSecret)
replaceCount = sbUrl.Replace("{code-parameter}",code)

respStr = http.QuickGetStr(sbUrl.GetAsString())
If (http.LastMethodSuccess <> 1) Then
    Response.Write "<pre>" & Server.HTMLEncode( http.LastErrorText) & "</pre>"
	Response.End 
End If

'  The response string will contain JSON like this:
' 
'  	{
' 	  "access_token": {access-token},
'  	  "token_type": {type},
'  	  "expires_in":	{seconds-til-expiration}
'  	}

set json = Server.CreateObject("Chilkat_9_5_0.JsonObject")
success = json.Load(respStr)

Response.Write "<p>access_token: " & json.StringOf("access_token") & "</p>"
Response.Write "<p>token_type: " & json.StringOf("token_type") & "</p>"
Response.Write "<p>expires_in: " & json.StringOf("expires_in") & "</p>"

' A sample result:
' access_token: EAAFaEtu5GRIBABb...wUXg05RFeaAZDZD
' token_type: bearer
' expires_in: 5180528

Facebook OAuth2 for Classic ASP – Step 1

This is a series of two posts to demonstrate implementing OAuth2 Authorization for Facebook in Classic ASP.
(Also see: Facebook OAuth2 for Classic ASP – Step 2)

The 1st step is to redirect to the Facebook Login Dialog where the Facebook account owner can grant access to the application.  Facebook will then return a response that redirects to your ASP page that implements Step 2.

Here is the ASP for Step 1:


AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth"
TokenEndpoint = "https://graph.facebook.com/oauth/access_token"

' Replace these with actual values.
AppId = "FACEBOOK-APP-ID"
AppSecret = "FACEBOOK-APP-SECRET"

' Set the Scope to a comma-separated list of permissions the app wishes to request.
' See https://developers.facebook.com/docs/facebook-login/permissions/ for a full list of permissions.
Scope = "public_profile,user_friends,email,user_posts,user_likes,user_photos,publish_actions"

' (State) Chilkat typically uses a 32 random bytes in base64url form.
' However, it can be anything (and any length), and doesn't need to be base64url encoded.
' For this example, I typed some random chars here:
State = "dkrh345y3895hyrtyowiurh3948rhteuirth"

' I'm using ngrok to callback to my web server running on localhost..
'RedirectUri = Server.URLEncode("https://www.your-website.com/fb_finishOAuth2.asp")
RedirectUri = Server.URLEncode("https://abca3bde.ngrok.io/fb_finishOAuth2.asp")

FbAuthUrl = AuthorizationEndpoint & "?response_type=code&scope=" & Scope & "&redirect_uri=" & RedirectUri & "&client_id=" & AppId & "&state=" & State

' Let's save our random state in a session variable.
Session("oauth2_state") = State

Response.Redirect FbAuthUrl

' Note: When I first used ngrok.io, I got the following error from Facebook:
'     Can't Load URL: The domain of this URL isn't included in the app's domains. 
'     To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
' 
' To fix, I temporarily changed my Facebook App's Site Url to https://abca3bde.ngrok.io/,
' and then added "abca3bde.ngrok.io" to the list of App Domains.