Skip to content

Instantly share code, notes, and snippets.

@james-dibble
Last active August 29, 2015 14:01
Show Gist options
  • Save james-dibble/16331b5db703f7369d96 to your computer and use it in GitHub Desktop.
Save james-dibble/16331b5db703f7369d96 to your computer and use it in GitHub Desktop.
Example controller for OAuth Authentication
namespace OAuthDemo.Controllers
{
using System;
using System.Web.Mvc;
[Authorize]
public class AccountController : Controller
{
public ActionResult Logout()
{
WebSecurity.Logout();
return this.RedirectToAction("index", "home");
}
[AllowAnonymous]
public ActionResult LoginExternal(string provider, string returnUrl)
{
// Create a URL for the authentication service to return too
var callback = this.Url.Action("verifyexternallogin", "account", new { returnUrl = returnUrl });
OAuthWebSecurity.RequestAuthentication(provider, callback);
}
[AllowAnonymous]
public ActionResult VerifyExternalLogin(string returnUrl)
{
var result = OAuthWebSecurity.VerifyAuthentication();
if (!result.IsSuccessful)
{
// Redirect to a view informing the user it failed
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, false))
{
// This external login has been used before, take the user back where they were
return this.RedirectToAction("loginredirect", "account", new { returnUrl = returnUrl });
}
// Add logic to create a record in your user table
// Create a record in the webpages_OAuthMembership table
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, result.UserName);
// Try to login again
OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, false);
// We've create a new user and they're logged in, take them back where they were
return this.Redirect(returnUrl);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment