Skip to content

Instantly share code, notes, and snippets.

@abjerner
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abjerner/70c1b2af2b3ea480e353 to your computer and use it in GitHub Desktop.
Save abjerner/70c1b2af2b3ea480e353 to your computer and use it in GitHub Desktop.
Facebook OAuth login
using System;
using Skybrud.Social.Facebook;
using Skybrud.Social.Facebook.OAuth;
namespace Skybrud.Social.Test.Facebook {
public partial class OAuth : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
FacebookOAuthClient oauth = new FacebookOAuthClient {
AppId = "---",
AppSecret = "---",
ReturnUri = "http://social.abjerner/Facebook/OAuth.aspx"
};
string code = Request.QueryString["code"];
string action = Request.QueryString["do"];
if (action == "login") {
// Get the redirect URI (if present)
string redirect = (Request.QueryString["redirect"] ?? "/");
// Set the state
string state = Guid.NewGuid().ToString();
Session["Facebook_" + state] = redirect;
// Construct the authorization URL
string authorizatioUrl = oauth.GetAuthorizationUrl(
state,
FacebookScope.ReadStream + FacebookScope.PublishStream
);
// Redirect the user to the OAuth dialog
Response.Redirect(authorizatioUrl);
} else if (code == null) {
Content.Text += "<a href=\"?do=login\" class=\"button\">Login with Facebook</a>";
} else {
// Get the state from the query string
string state = Request.QueryString["state"];
// Validate state - Step 1
if (state == null) {
Content.Text += "<div class=\"error\">No <strong>state</strong> specified in the query string.</div>";
return;
}
// Validate state - Step 2
string session = Session["Facebook_" + state] as string;
if (session == null) {
Content.Text += "<div class=\"error\">Session expired?</div>";
return;
}
// Remove the state from the session
Session.Remove("facebook_" + state);
// Exchange the auth code for an access token
string accessToken = oauth.GetAccessTokenFromAuthCode(code);
// Do your thing here
Content.Text += "<p><strong>Access token:</strong> " + accessToken + "</p>";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment