Enabling social logins

Removing hacks and using identity helpers.
This commit is contained in:
Praburaj 2014-09-24 16:42:05 -07:00
parent ef11294897
commit 3e6ce61f27
3 changed files with 53 additions and 56 deletions

View File

@ -1,11 +1,12 @@
using System.Linq; using System.Linq;
using System.Security.Principal; using System.Security.Principal;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Http.Security;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNet.Mvc.Rendering;
using MusicStore.Models; using MusicStore.Models;
using Microsoft.AspNet.Http;
using System.Security.Claims;
namespace MusicStore.Controllers namespace MusicStore.Controllers
{ {
@ -63,26 +64,20 @@ namespace MusicStore.Controllers
// //
// GET: /Account/VerifyCode // GET: /Account/VerifyCode
//TODO : Some of the identity helpers not implemented
[AllowAnonymous] [AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) public async Task<ActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{ {
//https://github.com/aspnet/Identity/issues/209 var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
// Require that the user has already logged in via username/password or external login if (user == null)
//if (!await SignInManager.HasBeenVerifiedAsync())
if ((await Context.AuthenticateAsync("Microsoft.AspNet.Identity.TwoFactor.UserId")).Identity.GetUserName() == null)
{ {
return View("Error"); return View("Error");
} }
//https://github.com/aspnet/Identity/issues/207 // Remove before production
//var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync());
var user = await UserManager.FindByIdAsync((await Context.AuthenticateAsync("Microsoft.AspNet.Identity.TwoFactor.UserId")).Identity.GetUserName());
#if DEMO #if DEMO
if (user != null) if (user != null)
{ {
var code = await UserManager.GenerateTwoFactorTokenAsync(user, provider); ViewBag.Code = await UserManager.GenerateTwoFactorTokenAsync(user, provider);
ViewBag.Code = code;
} }
#endif #endif
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
@ -104,7 +99,7 @@ namespace MusicStore.Controllers
// If a user enters incorrect codes for a specified amount of time then the user account // If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time. // will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig // You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberClient: model.RememberBrowser); var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
switch (result) switch (result)
{ {
case SignInStatus.Success: case SignInStatus.Success:
@ -174,6 +169,10 @@ namespace MusicStore.Controllers
} }
var user = await SignInManager.UserManager.FindByIdAsync(userId); var user = await SignInManager.UserManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(user, code); var result = await UserManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error"); return View(result.Succeeded ? "ConfirmEmail" : "Error");
} }
@ -208,7 +207,7 @@ namespace MusicStore.Controllers
var callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: Context.Request.Scheme); var callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: Context.Request.Scheme);
await UserManager.SendEmailAsync(user, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); await UserManager.SendEmailAsync(user, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
#if !DEMO #if !DEMO
return RedirectToAction("ForgotPasswordConfirmation", "Account"); return RedirectToAction("ForgotPasswordConfirmation");
#else #else
//To display the email link in a friendly page instead of sending email //To display the email link in a friendly page instead of sending email
ViewBag.Link = callbackUrl; ViewBag.Link = callbackUrl;
@ -235,6 +234,7 @@ namespace MusicStore.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult ResetPassword(string code) public ActionResult ResetPassword(string code)
{ {
//TODO: Fix this?
var resetPasswordViewModel = new ResetPasswordViewModel() { Code = code }; var resetPasswordViewModel = new ResetPasswordViewModel() { Code = code };
return code == null ? View("Error") : View(resetPasswordViewModel); return code == null ? View("Error") : View(resetPasswordViewModel);
} }
@ -281,8 +281,9 @@ namespace MusicStore.Controllers
public ActionResult ExternalLogin(string provider, string returnUrl = null) public ActionResult ExternalLogin(string provider, string returnUrl = null)
{ {
// Request a redirect to the external login provider // Request a redirect to the external login provider
var redirectUri = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
return new ChallengeResult(provider, new AuthenticationProperties() { RedirectUri = redirectUri }); var properties = Context.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
} }
// //
@ -290,14 +291,13 @@ namespace MusicStore.Controllers
[AllowAnonymous] [AllowAnonymous]
public async Task<ActionResult> SendCode(bool rememberMe, string returnUrl = null) public async Task<ActionResult> SendCode(bool rememberMe, string returnUrl = null)
{ {
//https://github.com/aspnet/Identity/issues/207 //TODO : Default rememberMe as well?
//var userId = await SignInManager.GetVerifiedUserIdAsync(); var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
var userId = (await Context.AuthenticateAsync("Microsoft.AspNet.Identity.TwoFactor.UserId")).Identity.GetUserName(); if (user == null)
if (userId == null)
{ {
return View("Error"); return View("Error");
} }
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(new ApplicationUser() { Id = userId }); var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
} }
@ -327,18 +327,14 @@ namespace MusicStore.Controllers
[AllowAnonymous] [AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null) public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null)
{ {
//TODO: Helper not available var loginInfo = await Context.GetExternalLoginInfo();
//var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
var loginInfo = await Context.AuthenticateAsync("External");
if (loginInfo == null) if (loginInfo == null)
{ {
return RedirectToAction("Login"); return RedirectToAction("Login");
} }
//TODO: Helper not available
// Sign in the user with this external login provider if the user already has a login // Sign in the user with this external login provider if the user already has a login
//var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); var result = await SignInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent: false);
var result = SignInStatus.Failure; //Always redirect to a login confirmation page for now.
switch (result) switch (result)
{ {
case SignInStatus.Success: case SignInStatus.Success:
@ -351,14 +347,15 @@ namespace MusicStore.Controllers
default: default:
// If the user does not have an account, then prompt the user to create an account // If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl; ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Identity.AuthenticationType; ViewBag.LoginProvider = loginInfo.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Identity.Claims.Single(c => c.Type == System.Security.Claims.ClaimTypes.Email).Value }); // REVIEW: handle case where email not in claims?
var email = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
} }
} }
// //
// POST: /Account/ExternalLoginConfirmation // POST: /Account/ExternalLoginConfirmation
// TODO: Some of the identity helpers not available
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
@ -372,8 +369,7 @@ namespace MusicStore.Controllers
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
// Get the information about the user from the external login provider // Get the information about the user from the external login provider
//var info = await AuthenticationManager.GetExternalLoginInfoAsync(); var info = await Context.GetExternalLoginInfo();
var info = await Context.AuthenticateAsync("External");
if (info == null) if (info == null)
{ {
return View("ExternalLoginFailure"); return View("ExternalLoginFailure");
@ -382,11 +378,9 @@ namespace MusicStore.Controllers
var result = await UserManager.CreateAsync(user); var result = await UserManager.CreateAsync(user);
if (result.Succeeded) if (result.Succeeded)
{ {
var userloginInfo = new UserLoginInfo(info.Description.AuthenticationType, info.Description.AuthenticationType, info.Description.Caption); result = await UserManager.AddLoginAsync(user, info);
result = await UserManager.AddLoginAsync(user, userloginInfo);
if (result.Succeeded) if (result.Succeeded)
{ {
// TODO: rememberBrowser option not being taken in SignInAsync
await SignInManager.SignInAsync(user, isPersistent: false); await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl); return RedirectToLocal(returnUrl);
} }

View File

@ -1,17 +1,17 @@
using System; using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Security.Principal; using System.Security.Principal;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using MusicStore.Models; using MusicStore.Models;
using System.Linq; using System.Linq;
using Microsoft.AspNet.Http.Security; using Microsoft.AspNet.Http;
namespace MusicStore.Controllers namespace MusicStore.Controllers
{ {
/// <summary> /// <summary>
/// Summary description for ManageController /// Summary description for ManageController
/// </summary> /// </summary>
[Authorize]
public class ManageController : Controller public class ManageController : Controller
{ {
public ManageController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) public ManageController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
@ -139,8 +139,9 @@ namespace MusicStore.Controllers
{ {
// This code allows you exercise the flow without actually sending codes // This code allows you exercise the flow without actually sending codes
// For production use please register a SMS provider in IdentityConfig and generate a code here. // For production use please register a SMS provider in IdentityConfig and generate a code here.
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); #if DEMO
ViewBag.Code = code; ViewBag.Code = await UserManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
#endif
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
} }
@ -282,6 +283,7 @@ namespace MusicStore.Controllers
{ {
ViewBag.StatusMessage = ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.Error ? "An error has occurred."
: ""; : "";
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
@ -290,8 +292,7 @@ namespace MusicStore.Controllers
return View("Error"); return View("Error");
} }
var userLogins = await UserManager.GetLoginsAsync(user); var userLogins = await UserManager.GetLoginsAsync(user);
var otherLogins = Context.GetAuthenticationTypes().Where(auth => auth.Caption != null && userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); var otherLogins = Context.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
//var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel return View(new ManageLoginsViewModel
{ {
@ -307,30 +308,31 @@ namespace MusicStore.Controllers
public ActionResult LinkLogin(string provider) public ActionResult LinkLogin(string provider)
{ {
// Request a redirect to the external login provider to link a login for the current user // Request a redirect to the external login provider to link a login for the current user
var authenticationProperties = new AuthenticationProperties() { RedirectUri = Url.Action("LinkLoginCallback", "Manage") }; var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
authenticationProperties.Dictionary[XsrfKey] = User.Identity.GetUserId(); var properties = Context.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.Identity.GetUserId());
return new ChallengeResult(provider, authenticationProperties); return new ChallengeResult(provider, properties);
} }
// //
// GET: /Manage/LinkLoginCallback // GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback() public async Task<ActionResult> LinkLoginCallback()
{ {
//var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); var user = await GetCurrentUserAsync();
var loginInfo = await Context.AuthenticateAsync("External"); if(user == null)
if (loginInfo == null || loginInfo.Properties.Dictionary[XsrfKey] != User.Identity.GetUserId()) {
return View("Error");
}
var loginInfo = await Context.GetExternalLoginInfo(User.Identity.GetUserId());
if (loginInfo == null)
{ {
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
} }
var user = new ApplicationUser() { Id = User.Identity.GetUserId() }; var result = await UserManager.AddLoginAsync(user, loginInfo);
var userloginInfo = new UserLoginInfo(loginInfo.Description.AuthenticationType, loginInfo.Description.AuthenticationType, loginInfo.Description.Caption); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
var result = await UserManager.AddLoginAsync(user, userloginInfo); return RedirectToAction("ManageLogins", new { Message = message });
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
} }
#region Helpers #region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private void AddErrors(IdentityResult result) private void AddErrors(IdentityResult result)
{ {
@ -340,6 +342,7 @@ namespace MusicStore.Controllers
} }
} }
//TODO: No caller - do we need this?
private async Task<bool> HasPhoneNumber() private async Task<bool> HasPhoneNumber()
{ {
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
@ -353,6 +356,7 @@ namespace MusicStore.Controllers
public enum ManageMessageId public enum ManageMessageId
{ {
AddPhoneSuccess, AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess, ChangePasswordSuccess,
SetTwoFactorSuccess, SetTwoFactorSuccess,
SetPasswordSuccess, SetPasswordSuccess,

View File

@ -1,11 +1,11 @@
@model MusicStore.Models.ExternalLoginListViewModel @model MusicStore.Models.ExternalLoginListViewModel
@using Microsoft.AspNet.Http;
@using Microsoft.AspNet.Http.Security; @using Microsoft.AspNet.Http.Security;
<h4>Use another service to log in.</h4> <h4>Use another service to log in.</h4>
<hr /> <hr />
@{ @{
//TODO: Need to replace with the helper that filters non external ones. GetExternalAuthenticationTypes() var loginProviders = Context.GetExternalAuthenticationTypes();
var loginProviders = Context.GetAuthenticationTypes();
if (loginProviders.Count() == 0) if (loginProviders.Count() == 0)
{ {
<div> <div>
@ -22,7 +22,6 @@
@Html.AntiForgeryToken() @Html.AntiForgeryToken()
<div id="socialLoginList"> <div id="socialLoginList">
<p> <p>
@*TODO: Temporary hack for the above issue. Needs to be removed once GetExternalAuthenticationTypes() is available*@
@foreach (AuthenticationDescription p in loginProviders.Where(a => a.Caption != null)) @foreach (AuthenticationDescription p in loginProviders.Where(a => a.Caption != null))
{ {
<button type="submit" class="btn btn-default" id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" title="Log in using your @p.Caption account">@p.AuthenticationType</button> <button type="submit" class="btn btn-default" id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" title="Log in using your @p.Caption account">@p.AuthenticationType</button>