Owin+ASP.NET Identity淺析系列(一)使用者登入註冊

來源:互聯網
上載者:User

標籤:manage   vs2015   arp   mysq   ret   引擎   key   com   技術   

在今天,讀書有時是件“麻煩”事。它需要你付出時間,付出精力,還要付出一份心境。--僅以《Owin+ASP.NET Identity淺析系列》來祭奠那逝去的……

  使用VS2015建立MVC項目運行之後,發現微軟很貼心的產生了一套使用者授權驗證系統,介面也很漂亮,但是扒拉代碼一看,囧……新的membership架構,真是太給力了,連資料庫表都給你產生了(EF的功勞),問題是,你這一堆一堆的代碼,雖然看著很吊(也

確實很吊),但是看著人頭大呢,只好研究研究,研究過程記錄一下,希望可以幫到那些看到這堆代碼之後也頭皮發麻的小夥伴們!!!

第一步:刪除這一堆代碼

  微軟折騰了一堆代碼,說實話對微軟的各種viewmodel驗證不感冒,所以我要刪除它,重新來過!喜歡使用的童鞋,可以保留

  備忘:親,別全部刪完,請保留IdentityModels類,修改下命名空間,並將其移入App_Start目錄中

  

第二步:拉出自動產生資料表的sql語句(因為後面使用的是mysql資料庫,而且引擎還不是innodb)

create table aspnetusers(Id char(32) primary key,Email varchar(50) null comment ‘使用者郵箱‘,EmailConfirmed bit not null comment ‘是否認證郵箱‘,PasswordHash varchar(100) null comment ‘賬戶密碼‘,SecurityStamp varchar(100) null comment ‘防偽印章‘,PhoneNumber varchar(100) null comment ‘使用者手機‘,PhoneNumberConfirmed bit not null comment ‘是否認證手機‘,TwoFactorEnabled bit not null comment ‘是否啟用雙重身分識別驗證‘,LockoutEndDateUtc datetime null comment ‘鎖定結束時間‘,LockoutEnabled bit not null comment ‘是否啟用鎖定‘,AccessFailedCount int not null comment ‘登陸失敗次數‘,UserName varchar(50) not null comment ‘使用者名稱稱‘) comment ‘使用者表‘;create table aspnetuserclaims(Id int auto_increment primary key,UserId char(32) not null comment ‘使用者Id‘,ClaimType varchar(100) null comment ‘ClaimType‘,ClaimValue varchar(100) null comment ‘ClaimValue‘) comment ‘claims表‘;create table aspnetuserlogins(UserId char(32) not null comment ‘‘,ProviderKey varchar(100) not null comment ‘‘,LoginProvider varchar(100) not null comment ‘‘) comment ‘登陸日誌表‘;create table aspnetuserroles(UserId char(32) not null comment ‘‘,RoleId char(32) not null comment ‘‘) comment ‘使用者角色表‘;create table aspnetroles(Id char(32) primary key,Name varchar(50) not null comment ‘‘) comment ‘使用者角色表‘;

第三步:修改ID的預設賦值,預設是36為GUID,修改為32位

    public class ApplicationUser : IdentityUser    {        public ApplicationUser()        {            this.Id = System.Guid.NewGuid().ToString("N");        }        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)        {            // 請注意,authenticationType 必須與 CookieAuthenticationOptions.AuthenticationType 中定義的相應項匹配            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);            // 在此處添加自訂使用者聲明            return userIdentity;        }    }

第四步:使用者登入,兩套代碼(一套是預設的登入方式,一套是自訂登入方式)

  預設登入方式代碼如下:

[HttpPost]public async Task<ActionResult> Login(string account, string password){    // 1. 利用ASP.NET Identity擷取使用者物件    var user = await UserManager.FindAsync(account, password);    if (user == null)        return Json(new { Flag = false, Content = "使用者名稱或密碼錯誤!!!" });    // 2. 利用ASP.NET Identity擷取identity 對象    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);    // 3. 將上面拿到的identity對象登入    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);    return Json(new { Flag = true, Content = "登入成功!!!" });}

   自訂登入方式代碼如下:

[HttpPost]public async Task<ActionResult> Login(string account, string password){    // 1. 利用ASP.NET Identity擷取使用者物件    var user = await UserManager.FindAsync(account, password);    if (user == null)        return Json(new { Flag = false, Content = "使用者名稱或密碼錯誤!!!" });    // 驗證使用者密碼和登入密碼是否一致,FindEmail等方法使用    // UserManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, password);    // 2. 利用ASP.NET Identity擷取identity 對象    claims.Add(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, user.Id));    claims.Add(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, user.UserName));    claims.Add(new System.Security.Claims.Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity"));    claims.Add(new System.Security.Claims.Claim("AspNet.Identity.SecurityStamp", user.SecurityStamp));        // 這裡可以自訂角色或其他資料    // claims.Add(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, "user"));    //聲明身分識別驗證方式    var identity = new System.Security.Claims.ClaimsIdentity("ApplicationCookie");    identity.AddClaims(claims);    // 3. 將上面拿到的identity對象登入    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);    return Json(new { Flag = true, Content = "登入成功!!!" });}

 

Owin+ASP.NET Identity淺析系列(一)使用者登入註冊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.