Change Primary Key for Users in ASP.NET Identity
In Visual Studio 2013, the default web application uses a string value for the key for user accounts. ASP.NET Identity enables you to change the type of the key to meet your data requirements. For example, you can change the type of the key from a string to an integer.
This topic shows how to start with the default web application and change the user account key to an integer. You can use the same modifications to implement any type of key in your project. It shows how to make these changes in the default web application, but you could apply similar modifications to a customized application. It shows the changes needed when working with MVC or Web Forms.
Software versions used in the tutorial
- Visual Studio 2013 with Update 2 (or later)
- ASP.NET Identity 2.1 or later
To perform the steps in this tutorial, you must have Visual Studio 2013 Update 2 (or later), and a web application created from the ASP.NET Web Application template. The template changed in Update 3. This topic shows how to change the template in Update 2 and Update 3.
This topic contains the following sections:
- Change the type of the key in the Identity user class
- Add customized Identity classes that use the key type
- Change the context class and user manager to use the key type
- Change start-up configuration to use the key type
- For MVC with Update 2, change the AccountController to pass the key type
- For MVC with Update 3, change the AccountController and ManageController to pass the key type
- For Web Forms with Update 2, change Account pages to pass the key type
- For Web Forms with Update 3, change Account pages to pass the key type
- Run application
- Other resources
Change the type of the key in the Identity user class
In your project created from the ASP.NET Web Application template, specify that the ApplicationUser class uses an integer for the key for user accounts. In IdentityModels.cs, change the ApplicationUser class to inherit from IdentityUser that has a type of int for the TKey generic parameter. You also pass the names of three customized class which you have not implemented yet.
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
...
You have changed the type of the key, but, by default, the rest of the application still assumes the key is a string. You must explicitly indicate the type of the key in code that assumes a string.
In the ApplicationUser class, change the GenerateUserIdentityAsync method to include int, as shown in the highlighted code below. This change is not necessary for Web Forms projects with the Update 3 template.
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
UserManager<ApplicationUser, int> manager)
{
// Note the authenticationType must match the one defined in
// CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(
this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
Add customized Identity classes that use the key type
The other Identity classes, such as IdentityUserRole, IdentityUserClaim, IdentityUserLogin, IdentityRole, UserStore, RoleStore, are still set up to use a string key. Create new versions of these classes that specify an integer for the key. You do not need to provide much implementation code in these classes, you are primarily just setting int as the key.
Add the following classes to your IdentityModels.cs file.
public class CustomUserRole : IdentityUserRole<int> { }
public class CustomUserClaim : IdentityUserClaim<int> { }
public class CustomUserLogin : IdentityUserLogin<int> { }
public class CustomRole : IdentityRole<int, CustomUserRole>
{
public CustomRole() { }
public CustomRole(string name) { Name = name; }
}
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int,
CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public CustomUserStore(ApplicationDbContext context)
: base(context)
{
}
}
public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
{
public CustomRoleStore(ApplicationDbContext context)
: base(context)
{
}
}
Change the context class and user manager to use the key type
In IdentityModels.cs, change the definition of the ApplicationDbContext class to use your new customized classes and an int for the key, as shown in the highlighted code.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole,
int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
...
The ThrowIfV1Schema parameter is no longer valid in the constructor. Change the constructor so it does not pass a ThrowIfV1Schema value.
public ApplicationDbContext()
: base("DefaultConnection")
{
}
Open IdentityConfig.cs, and change the ApplicationUserManger class to use your new user store class for persisting data and an int for the key.
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
: base(store)
{
}
public static ApplicationUserManager Create(
IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(
new CustomUserStore(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Register two factor authentication providers. This application uses Phone
// and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode",
new PhoneNumberTokenProvider<ApplicationUser, int>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode",
new EmailTokenProvider<ApplicationUser, int>
{
Subject = "Security Code",
BodyFormat = "Your security code is: {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser, int>(
dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
In the Update 3 template, you must change the ApplicationSignInManager class.
public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
{ ... }
Change start-up configuration to use the key type
In Startup.Auth.cs, replace the OnValidateIdentity code, as highlighted below. Notice that the getUserIdCallback definition, parses the string value into an integer.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator
.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) =>
user.GenerateUserIdentityAsync(manager),
getUserIdCallback:(id)=>(id.GetUserId<int>()))
}
});
If your project does not recognize the generic implementation of the GetUserId method, you may need to update the ASP.NET Identity NuGet package to version 2.1
You have made a lot of changes to the infrastructure classes used by ASP.NET Identity. If you try compiling the project, you will notice a lot of errors. Fortunately, the remaining errors are all similar. The Identity class expects an integer for the key, but the controller (or Web Form) is passing a string value. In each case, you need to convert from a string to and integer by calling GetUserId<int>. You can either work through the error list from compilation or follow the changes below.
The remaining changes depend on the type of project you are creating and which update you have installed in Visual Studio. You can go directly to the relevant section through the following links
- For MVC with Update 2, change the AccountController to pass the key type
- For MVC with Update 3, change the AccountController and ManageController to pass the key type
- For Web Forms with Update 2, change Account pages to pass the key type
- For Web Forms with Update 3, change Account pages to pass the key type
For MVC with Update 2, change the AccountController to pass the key type
Open the AccountController.cs file. You need to change the following methods.
ConfirmEmail method
public async Task<ActionResult> ConfirmEmail(int userId, string code)
{
if (userId == default(int) || code == null)
{
return View("Error");
}
IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
return View("ConfirmEmail");
}
else
{
AddErrors(result);
return View();
}
}
Disassociate method
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
ManageMessageId? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(
User.Identity.GetUserId<int>(),
new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
await SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
Manage(ManageUserViewModel) method
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
bool hasPassword = HasPassword();
ViewBag.HasLocalPassword = hasPassword;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasPassword)
{
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.ChangePasswordAsync(
User.Identity.GetUserId<int>(),
model.OldPassword,
model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(
User.Identity.GetUserId<int>());
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Manage", new {
Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
else
{
// User does not have a password so remove any validation errors caused
// by a missing OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.AddPasswordAsync(
User.Identity.GetUserId<int>(), model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new {
Message = ManageMessageId.SetPasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
LinkLoginCallback method
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey,
User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
IdentityResult result = await UserManager.AddLoginAsync(
User.Identity.GetUserId<int>(), loginInfo.Login);
if (result.Succeeded)
{
return RedirectToAction("Manage");
}
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
RemoveAccountList method
public ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId<int>());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
HasPassword method
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
You can now run the application and register a new user.
For MVC with Update 3, change the AccountController and ManageController to pass the key type
Open the AccountController.cs file. You need to change the following method.
ConfirmEmail method
public async Task<ActionResult> ConfirmEmail(int userId, string code)
{
if (userId == default(int) || code == null)
{
return View("Error");
}
IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
SendCode method
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == default(int))
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
Open the ManageController.cs file. You need to change the following methods.
Index method
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId<int>()),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId<int>()),
Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId<int>()),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(
User.Identity.GetUserId())
};
return View(model);
}
RemoveLogin methods
public ActionResult RemoveLogin()
{
var linkedAccounts = UserManager.GetLogins((User.Identity.GetUserId<int>()));
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId<int>(),
new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("ManageLogins", new { Message = message });
}
AddPhoneNumber method
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(
User.Identity.GetUserId<int>(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await UserManager.SmsService.SendAsync(message);
}
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
EnableTwoFactorAuthentication method
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId<int>(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", "Manage");
}
DisableTwoFactorAuthentication method
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId<int>(), false);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", "Manage");
}
VerifyPhoneNumber methods
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(
User.Identity.GetUserId<int>(), phoneNumber);
// Send an SMS through the SMS provider to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePhoneNumberAsync(
User.Identity.GetUserId<int>(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Failed to verify phone");
return View(model);
}
RemovePhoneNumber method
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId<int>(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
ChangePassword method
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(
User.Identity.GetUserId<int>(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
SetPassword method
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId<int>(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user != null)
{
await SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
ManageLogins method
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId<int>());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
LinkLoginCallback method
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId<int>(),
loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") :
RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
HasPassword method
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
HasPhoneNumber method
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
You can now run the application and register a new user.
For Web Forms with Update 2, change Account pages to pass the key type
For Web Forms with Update 2, you need to change the following pages.
Confirm.aspx.cx
protected void Page_Load(object sender, EventArgs e)
{
string code = IdentityHelper.GetCodeFromRequest(Request);
string userId = IdentityHelper.GetUserIdFromRequest(Request);
if (code != null && userId != null)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = manager.ConfirmEmail(Int32.Parse(userId), code);
if (result.Succeeded)
{
StatusMessage = "Thank you for confirming your account.";
return;
}
}
StatusMessage = "An error has occurred";
}
RegisterExternalLogin.aspx.cs
protected void Page_Load()
{
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
RedirectOnFail();
return;
}
if (!IsPostBack)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication
.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
RedirectOnFail();
return;
}
var result = manager.AddLogin(User.Identity.GetUserId<int>(),
verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"],
Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
email.Text = loginInfo.Email;
}
}
}
Manage.aspx.cs
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId<int>());
}
protected void Page_Load()
{
if (!IsPostBack)
{
// Determine the sections to render
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
if (HasPassword(manager))
{
changePasswordHolder.Visible = true;
}
else
{
setPassword.Visible = true;
changePasswordHolder.Visible = false;
}
CanRemoveExternalLogins = manager.GetLogins(
User.Identity.GetUserId<int>()).Count() > 1;
// Render success message
var message = Request.QueryString["m"];
if (message != null)
{
// Strip the query string from action
Form.Action = ResolveUrl("~/Account/Manage");
SuccessMessage =
message == "ChangePwdSuccess" ? "Your password has been changed."
: message == "SetPwdSuccess" ? "Your password has been set."
: message == "RemoveLoginSuccess" ? "The account was removed."
: String.Empty;
successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
}
}
}
protected void ChangePassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult result = manager.ChangePassword(
User.Identity.GetUserId<int>(),
CurrentPassword.Text,
NewPassword.Text);
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId<int>());
IdentityHelper.SignIn(manager, user, isPersistent: false);
Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
}
else
{
AddErrors(result);
}
}
}
protected void SetPassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
// Create the local login info and link the local account to the user
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult result = manager.AddPassword(User.Identity.GetUserId<int>(),
password.Text);
if (result.Succeeded)
{
Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
}
else
{
AddErrors(result);
}
}
}
public IEnumerable<UserLoginInfo> GetLogins()
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var accounts = manager.GetLogins(User.Identity.GetUserId<int>());
CanRemoveExternalLogins = accounts.Count() > 1 || HasPassword(manager);
return accounts;
}
public void RemoveLogin(string loginProvider, string providerKey)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = manager.RemoveLogin(User.Identity.GetUserId<int>(),
new UserLoginInfo(loginProvider, providerKey));
string msg = String.Empty;
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId<int>());
IdentityHelper.SignIn(manager, user, isPersistent: false);
msg = "?m=RemoveLoginSuccess";
}
Response.Redirect("~/Account/Manage" + msg);
}
You can now run the application and register a new user.
For Web Forms with Update 3, change Account pages to pass the key type
For Web Forms with Update 3, you need to change the following pages.
Confirm.aspx.cx
protected void Page_Load(object sender, EventArgs e)
{
string code = IdentityHelper.GetCodeFromRequest(Request);
string userId = IdentityHelper.GetUserIdFromRequest(Request);
if (code != null && userId != null)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = manager.ConfirmEmail(Int32.Parse(userId), code);
if (result.Succeeded)
{
StatusMessage = "Thank you for confirming your account.";
return;
}
}
StatusMessage = "An error has occurred";
}
RegisterExternalLogin.aspx.cs
protected void Page_Load()
{
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
RedirectOnFail();
return;
}
if (!IsPostBack)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication
.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
RedirectOnFail();
return;
}
var result = manager.AddLogin(User.Identity.GetUserId<int>(),
verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"],
Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
email.Text = loginInfo.Email;
}
}
}
Manage.aspx.cs
public partial class Manage : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId<int>());
}
public bool HasPhoneNumber { get; private set; }
public bool TwoFactorEnabled { get; private set; }
public bool TwoFactorBrowserRemembered { get; private set; }
public int LoginsCount { get; set; }
protected void Page_Load()
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
HasPhoneNumber = String.IsNullOrEmpty(manager.GetPhoneNumber(
User.Identity.GetUserId<int>()));
// Enable this after setting up two-factor authentientication
//PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty;
TwoFactorEnabled = manager.GetTwoFactorEnabled(User.Identity.GetUserId<int>());
LoginsCount = manager.GetLogins(User.Identity.GetUserId<int>()).Count;
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
if (!IsPostBack)
{
// Determine the sections to render
if (HasPassword(manager))
{
ChangePassword.Visible = true;
}
else
{
CreatePassword.Visible = true;
ChangePassword.Visible = false;
}
// Render success message
var message = Request.QueryString["m"];
if (message != null)
{
// Strip the query string from action
Form.Action = ResolveUrl("~/Account/Manage");
SuccessMessage =
message == "ChangePwdSuccess" ? "Your password has been changed."
: message == "SetPwdSuccess" ? "Your password has been set."
: message == "RemoveLoginSuccess" ? "The account was removed."
: message == "AddPhoneNumberSuccess" ? "Phone number has been added"
: message == "RemovePhoneNumberSuccess" ? "Phone number was removed"
: String.Empty;
successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
}
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
// Remove phonenumber from user
protected void RemovePhone_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = manager.SetPhoneNumber(User.Identity.GetUserId<int>(), null);
if (!result.Succeeded)
{
return;
}
var user = manager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess");
}
}
// DisableTwoFactorAuthentication
protected void TwoFactorDisable_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
manager.SetTwoFactorEnabled(User.Identity.GetUserId<int>(), false);
Response.Redirect("/Account/Manage");
}
//EnableTwoFactorAuthentication
protected void TwoFactorEnable_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
manager.SetTwoFactorEnabled(User.Identity.GetUserId<int>(), true);
Response.Redirect("/Account/Manage");
}
}
VerifyPhoneNumber.aspx.cs
public partial class VerifyPhoneNumber : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var phonenumber = Request.QueryString["PhoneNumber"];
var code = manager.GenerateChangePhoneNumberToken(
User.Identity.GetUserId<int>(), phonenumber);
PhoneNumber.Value = phonenumber;
}
protected void Code_Click(object sender, EventArgs e)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", "Invalid code");
return;
}
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = manager.ChangePhoneNumber(
User.Identity.GetUserId<int>(), PhoneNumber.Value, Code.Text);
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
IdentityHelper.SignIn(manager, user, false);
Response.Redirect("/Account/Manage?m=AddPhoneNumberSuccess");
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Failed to verify phone");
}
}
AddPhoneNumber.aspx.cs
public partial class AddPhoneNumber : System.Web.UI.Page
{
protected void PhoneNumber_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var code = manager.GenerateChangePhoneNumberToken(
User.Identity.GetUserId<int>(), PhoneNumber.Text);
if (manager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = PhoneNumber.Text,
Body = "Your security code is " + code
};
manager.SmsService.Send(message);
}
Response.Redirect("/Account/VerifyPhoneNumber?PhoneNumber=" + HttpUtility.UrlEncode(PhoneNumber.Text));
}
}
ManagePassword.aspx.cs
public partial class ManagePassword : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId<int>());
}
protected void Page_Load(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
if (!IsPostBack)
{
// Determine the sections to render
if (HasPassword(manager))
{
changePasswordHolder.Visible = true;
}
else
{
setPassword.Visible = true;
changePasswordHolder.Visible = false;
}
// Render success message
var message = Request.QueryString["m"];
if (message != null)
{
// Strip the query string from action
Form.Action = ResolveUrl("~/Account/Manage");
}
}
}
protected void ChangePassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult result = manager.ChangePassword(
User.Identity.GetUserId<int>(), CurrentPassword.Text, NewPassword.Text);
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId<int>());
IdentityHelper.SignIn(manager, user, isPersistent: false);
Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
}
else
{
AddErrors(result);
}
}
}
protected void SetPassword_Click(object sender, EventArgs e)
{
if (IsValid)
{
// Create the local login info and link the local account to the user
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult result = manager.AddPassword(
User.Identity.GetUserId<int>(), password.Text);
if (result.Succeeded)
{
Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
}
else
{
AddErrors(result);
}
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
ManageLogins.aspx.cs
public partial class ManageLogins : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
protected bool CanRemoveExternalLogins
{
get;
private set;
}
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId<int>());
}
protected void Page_Load(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
CanRemoveExternalLogins = manager.GetLogins(
User.Identity.GetUserId<int>()).Count() > 1;
SuccessMessage = String.Empty;
successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
}
public IEnumerable<UserLoginInfo> GetLogins()
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var accounts = manager.GetLogins(User.Identity.GetUserId<int>());
CanRemoveExternalLogins = accounts.Count() > 1 || HasPassword(manager);
return accounts;
}
public void RemoveLogin(string loginProvider, string providerKey)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var result = manager.RemoveLogin(
User.Identity.GetUserId<int>(), new UserLoginInfo(loginProvider, providerKey));
string msg = String.Empty;
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId<int>());
IdentityHelper.SignIn(manager, user, isPersistent: false);
msg = "?m=RemoveLoginSuccess";
}
Response.Redirect("~/Account/ManageLogins" + msg);
}
}
TwoFactorAuthenticationSignIn.aspx.cs
public partial class TwoFactorAuthenticationSignIn : System.Web.UI.Page
{
private ApplicationSignInManager signinManager;
private ApplicationUserManager manager;
public TwoFactorAuthenticationSignIn()
{
manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
}
protected void Page_Load(object sender, EventArgs e)
{
var userId = signinManager.GetVerifiedUserId<ApplicationUser, int>();
if (userId == default(int))
{
Response.Redirect("/Account/Error", true);
}
var userFactors = manager.GetValidTwoFactorProviders(userId);
Providers.DataSource = userFactors.Select(x => x).ToList();
Providers.DataBind();
}
protected void CodeSubmit_Click(object sender, EventArgs e)
{
bool rememberMe = false;
bool.TryParse(Request.QueryString["RememberMe"], out rememberMe);
var result = signinManager.TwoFactorSignIn<ApplicationUser, int>(SelectedProvider.Value, Code.Text, isPersistent: rememberMe, rememberBrowser: RememberBrowser.Checked);
switch (result)
{
case SignInStatus.Success:
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
case SignInStatus.LockedOut:
Response.Redirect("/Account/Lockout");
break;
case SignInStatus.Failure:
default:
FailureText.Text = "Invalid code";
ErrorMessage.Visible = true;
break;
}
}
protected void ProviderSubmit_Click(object sender, EventArgs e)
{
if (!signinManager.SendTwoFactorCode(Providers.SelectedValue))
{
Response.Redirect("/Account/Error");
}
var user = manager.FindById(signinManager.GetVerifiedUserId<ApplicationUser, int>());
if (user != null)
{
var code = manager.GenerateTwoFactorToken(user.Id, Providers.SelectedValue);
}
SelectedProvider.Value = Providers.SelectedValue;
sendcode.Visible = false;
verifycode.Visible = true;
}
}
Run application
You have finished all of the required changes to the default Web Application template. Run the application and register a new user. After registering the user, you will notice that the AspNetUsers table has an Id column that is an integer.
If you have previously created the ASP.NET Identity tables with a different primary key, you need to make some additional changes. If possible, just delete the existing database. The database will be re-created with the correct design when you run the web application and add a new user. If deletion is not possible, run code first migrations to change the tables. However, the new integer primary key will not be set up as a SQL IDENTITY property in the database. You must manually set the Id column as an IDENTITY.