在 ASP.NET Identity 中更改用户的主键
在 Visual Studio 2013 中,默认 Web 应用程序使用字符串值作为用户帐户的密钥。 ASP.NET Identity 使你可以更改密钥的类型以满足数据要求。 例如,可以将键的类型从字符串更改为整数。
本主题演示如何从默认 Web 应用程序开始并将用户帐户密钥更改为整数。 可以使用相同的修改在项目中实现任何类型的密钥。 它演示了如何在默认 Web 应用程序中进行这些更改,但你可以对自定义应用程序应用类似的修改。 它显示了使用 MVC 或Web Forms时所需的更改。
本教程中使用的软件版本
- 使用 Update 2 (或更高版本) Visual Studio 2013
- ASP.NET Identity 2.1 或更高版本
若要执行本教程中的步骤,必须Visual Studio 2013 Update 2 (或更高版本) ,以及从 ASP.NET Web 应用程序模板创建的 Web 应用程序。 模板在 Update 3 中更改。 本主题演示如何在 Update 2 和 Update 3 中更改模板。
本主题包含以下各节:
- 更改 Identity 用户类中密钥的类型
- 添加使用密钥类型的自定义标识类
- 将上下文类和用户管理器更改为使用密钥类型
- 将启动配置更改为使用密钥类型
- 对于具有 Update 2 的 MVC,请更改 AccountController 以传递密钥类型
- 对于具有 Update 3 的 MVC,请更改 AccountController 和 ManageController 以传递密钥类型
- 对于 Update 2 的Web Forms,请更改“帐户”页面以传递密钥类型
- 对于 Update 3 的Web Forms,请更改“帐户”页面以传递密钥类型
- 运行应用程序
- 其他资源
更改 Identity 用户类中密钥的类型
在从 ASP.NET Web 应用程序模板创建的项目中,指定 ApplicationUser 类使用一个整数作为用户帐户的密钥。 在 IdentityModels.cs 中,将 ApplicationUser 类更改为从 TKey 泛型参数的类型为 int 的 IdentityUser 继承。 还会传递尚未实现的三个自定义类的名称。
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
...
你已更改了密钥的类型,但默认情况下,应用程序的其余部分仍假定密钥是字符串。 必须在假定字符串的代码中显式指示密钥的类型。
在 ApplicationUser 类中,将 GenerateUserIdentityAsync 方法更改为包含 int,如下面突出显示的代码所示。 对于使用 Update 3 模板Web Forms项目,不需要进行此更改。
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;
}
添加使用密钥类型的自定义标识类
其他标识类(如 IdentityUserRole、IdentityUserClaim、IdentityUserLogin、IdentityRole、UserStore、RoleStore)仍设置为使用字符串密钥。 创建这些类的新版本,以指定键的整数。 无需在这些类中提供太多实现代码,主要只需将 int 设置为键。
将以下类添加到 IdentityModels.cs 文件。
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)
{
}
}
将上下文类和用户管理器更改为使用密钥类型
在 IdentityModels.cs 中,更改 ApplicationDbContext 类的定义,以使用新的自定义类和 int 作为密钥,如突出显示的代码所示。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole,
int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
...
ThrowIfV1Schema 参数在构造函数中不再有效。 更改构造函数,使其不传递 ThrowIfV1Schema 值。
public ApplicationDbContext()
: base("DefaultConnection")
{
}
打开 IdentityConfig.cs,将 ApplicationUserManger 类更改为使用新的用户存储类来保存数据,并使用 int 作为密钥。
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;
}
}
在 Update 3 模板中,必须更改 ApplicationSignInManager 类。
public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
{ ... }
将启动配置更改为使用密钥类型
在 Startup.Auth.cs 中,替换 OnValidateIdentity 代码,如下所示。 请注意,getUserIdCallback 定义将字符串值分析为整数。
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>()))
}
});
如果项目无法识别 GetUserId 方法的泛型实现,则可能需要将 ASP.NET Identity NuGet 包更新到版本 2.1
你对 ASP.NET Identity 使用的基础结构类进行了大量更改。 如果尝试编译项目,你会注意到很多错误。 幸运的是,其余错误都类似。 Identity 类需要密钥的整数,但控制器 (或 Web 窗体) 传递字符串值。 在每种情况下,都需要通过调用 GetUserId<int> 将字符串转换为 和 整数。 可以从编译中查看错误列表,也可以按照以下更改进行操作。
其余更改取决于要创建的项目类型和在 Visual Studio 中安装的更新。 可以通过以下链接直接转到相关部分
- 对于具有 Update 2 的 MVC,请更改 AccountController 以传递密钥类型
- 对于具有 Update 3 的 MVC,请更改 AccountController 和 ManageController 以传递密钥类型
- 对于 Update 2 的Web Forms,请更改“帐户”页面以传递密钥类型
- 对于 Update 3 的Web Forms,请更改“帐户”页面以传递密钥类型
对于具有 Update 2 的 MVC,请更改 AccountController 以传递密钥类型
打开 AccountController.cs 文件。 需要更改以下方法。
ConfirmEmail 方法
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();
}
}
取消关联 方法
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 });
}
管理 (ManageUserViewModel) 方法
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 方法
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 方法
public ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId<int>());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
HasPassword 方法
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
现在可以 运行应用程序 并注册新用户。
对于具有 Update 3 的 MVC,请更改 AccountController 和 ManageController 以传递密钥类型
打开 AccountController.cs 文件。 需要更改以下方法。
ConfirmEmail 方法
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 方法
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 });
}
打开 ManageController.cs 文件。 需要更改以下方法。
Index 方法
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 方法
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 方法
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 方法
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 方法
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 方法
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 方法
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 方法
[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 方法
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 方法
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 方法
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 方法
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
HasPhoneNumber 方法
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
现在可以 运行应用程序 并注册新用户。
对于 Update 2 的Web Forms,请更改“帐户”页面以传递密钥类型
对于 Update 2 的Web Forms,需要更改以下页面。
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);
}
现在可以 运行应用程序 并注册新用户。
对于 Update 3 的Web Forms,请更改“帐户”页面以传递密钥类型
对于 Update 3 的Web Forms,需要更改以下页面。
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;
}
}
运行应用程序
你已完成对默认 Web 应用程序模板的所有必需更改。 运行应用程序并注册新用户。 注册用户后,你会注意到 AspNetUsers 表的 Id 列是整数。
如果之前已使用不同的主键创建了 ASP.NET Identity 表,则需要进行一些其他更改。 如果可能,只需删除现有数据库即可。 运行 Web 应用程序并添加新用户时,将使用正确的设计重新创建数据库。 如果无法删除,请首先运行代码迁移以更改表。 但是,新的整数主键不会在数据库中设置为 SQL IDENTITY 属性。 必须手动将 ID 列设置为 IDENTITY。