Last active
August 29, 2015 14:01
-
-
Save james-dibble/16331b5db703f7369d96 to your computer and use it in GitHub Desktop.
Example controller for OAuth Authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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