一、建立ClaimsIdentity
ClaimsIdentity(委託宣告式身分識別)是在ASP.NET Identity身份認證系統的登入時要用到,我們在UserService中來產生它。
1、開啟IBLL項目InterfaceUserService介面,添加介面方法ClaimsIdentity CreateIdentity(User user, string authenticationType);
2、開啟BLL項目的UserService類,添加CreateIdentity方法的實現代碼
public ClaimsIdentity CreateIdentity(User user, string authenticationType) { ClaimsIdentity _identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); _identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); _identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString())); _identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity")); _identity.AddClaim(new Claim("DisplayName", user.DisplayName)); return _identity; }
二、擷取AuthenticationManager(認證管理器)
開啟Ninesky.Web項目 Member地區的UserController,添加AuthenticationManager屬性,在HttpContext.GetOwinContext()中擷取這個屬性。
#region 屬性 private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } #endregion
三、建立登入視圖模型
Member地區的模型檔案夾添加視圖模型
using System.ComponentModel.DataAnnotations;namespace Ninesky.Web.Areas.Member.Models{ /// <summary> /// 登入模型 /// <remarks> /// 建立:2014.02.16 /// </remarks> /// </summary> public class LoginViewModel { /// <summary> /// 使用者名稱 /// </summary> [Required(ErrorMessage = "必填")] [StringLength(20, MinimumLength = 4, ErrorMessage = "{2}到{1}個字元")] [Display(Name = "使用者名稱")] public string UserName { get; set; } /// <summary> /// 密碼 /// </summary> [Required(ErrorMessage = "必填")] [Display(Name = "密碼")] [StringLength(20, MinimumLength = 6, ErrorMessage = "{2}到{1}個字元")] [DataType(DataType.Password)] public string Password { get; set; } /// <summary> /// 記住我 /// </summary> [Display(Name = "記住我")] public bool RememberMe { get; set; } }}
四、建立登入頁面
在UserCcontroller中添加(string returnUrl) action
/// <summary> /// 使用者登入 /// </summary> /// <param name="returnUrl">返回Url</param> /// <returns></returns> public ActionResult Login(string returnUrl) { return View(); }
右鍵添加強型別視圖,模型為LoginViewModel
@model Ninesky.Web.Areas.Member.Models.LoginViewModel@{ ViewBag.Title = "會員登入";}@using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>會員登入</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.UserName, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.UserName) @Html.ValidationMessageFor(model => model.UserName) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.RememberMe, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.RememberMe) @Html.ValidationMessageFor(model => model.RememberMe) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="登入" class="btn btn-default" /> </div> </div> </div>}@section Scripts { @Scripts.Render("~/bundles/jqueryval")}
效果
五、建立使用者登入處理action
在UserCcontroller中添加 httppost類型的 Login action中先用ModelState.IsValid看模型驗證是否通過,沒通過直接返回,通過則檢查使用者密碼是否正確。使用者名稱密碼正確用CreateIdentity方法建立標識,然後用SignOut方法清空Cookies,然後用SignIn登入。
[ValidateAntiForgeryToken] [HttpPost] public ActionResult Login(LoginViewModel loginViewModel) { if(ModelState.IsValid) { var _user = userService.Find(loginViewModel.UserName); if (_user == null) ModelState.AddModelError("UserName", "使用者名稱不存在"); else if (_user.Password == Common.Security.Sha256(loginViewModel.Password)) { var _identity = userService.CreateIdentity(_user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = loginViewModel.RememberMe }, _identity); return RedirectToAction("Index", "Home"); } else ModelState.AddModelError("Password", "密碼錯誤"); } return View(); }
六、修改使用者註冊代碼
讓使用者註冊成功後直接登入
七、登出
在UserCcontroller中添加在Logout action
/// <summary> /// 登出 /// </summary> /// <returns></returns> public ActionResult Logout() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return Redirect(Url.Content("~/")); }
本文已被整理到了《ASP.NET MVC網站開發教程》,歡迎大家學習閱讀,更多內容還可以參考ASP.NET MVC5網站開發專題學習。
本文主要是用到了ClaimsIdentity(宣告式身分識別)、AuthenticationManager的SignOut、SignIn方法。希望對大家實現使用者註冊和登出有所協助。