Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created March 11, 2015 08:58
Show Gist options
  • Save AlexArchive/3936c9a73f0f181151b3 to your computer and use it in GitHub Desktop.
Save AlexArchive/3936c9a73f0f181151b3 to your computer and use it in GitHub Desktop.
public class AccountController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login()
{
var redirectUri = Url.Action(
"ExternalLoginCallback",
"Account");
return new ChallengeResult(redirectUri);
}
public ActionResult ExternalLoginCallback()
{
var context = new ApplicationContext();
var userStore = new UserStore<IdentityUser>(context);
var userManager = new UserManager<IdentityUser>(userStore);
var authentication = HttpContext.GetOwinContext().Authentication;
var signInManager = new SignInManager<IdentityUser, string>(userManager, authentication);
var account = authentication.GetExternalLoginInfo();
var status = signInManager.ExternalSignIn(account, false);
switch (status)
{
case SignInStatus.Success:
{
return RedirectToAction("Index", "Home");
}
case SignInStatus.Failure:
{
var user = new IdentityUser
{
UserName = account.DefaultUserName,
Email = account.Email
};
var operation = userManager.Create(user);
if (operation.Succeeded)
{
operation = userManager.AddLogin(user.Id, account.Login);
if (operation.Succeeded)
{
signInManager.SignIn(
user: user,
isPersistent: false,
rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
}
}
break;
}
throw new HttpException(500, "This should not be happening.");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Logout()
{
var authentication = HttpContext.GetOwinContext().Authentication;
authentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
public class ChallengeResult : HttpUnauthorizedResult
{
public string RedirectUri { get; set; }
public ChallengeResult(string redirectUri)
{
RedirectUri = redirectUri;
}
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties {RedirectUri = RedirectUri};
context.HttpContext
.GetOwinContext()
.Authentication
.Challenge(properties, "GitHub");
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseGitHubAuthentication(new GitHubAuthenticationOptions
{
ClientId = "dc2119b9f611c6fec9c6",
ClientSecret = "d028ee0e40ed333e53efa5dd2aba3e0e56bbfbee",
Scope = { "" }
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment