網站登入實作


網站登入的實際範例,本次參考資料:[ASP.NET] ASP.NET Identity 中 ClaimsIdentity 解析

下列範例中僅有關鍵部分,細節都略去了,如果還要甚麼登入 Log、IP 判斷,就自行再找地方加上去吧

// 在登入之前先將使用者登出
if (User.Identity.IsAuthenticated)
{
    // SignOut這裡的字串最好用常數字串來處理,避免手誤跟別的地方key不一樣發生各種靈異事件
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    Session.Clear();
}

// 驗證使用者登入帳號、密碼,通過驗證則返回 User DTO;失敗返回 null
// 驗證使用者登入的部分,可實作多種驗證方式,例如 AD 或是普通的帳號密碼
// 此處範例僅用普通的驗證帳密
if (isVeryUser(account,password)){
   var identity = new ClaimsIdentity(
    new[]
        {
            new Claim(ClaimTypes.NameIdentifier, id.ToString()),
            new Claim(ClaimTypes.Name, name),
            new Claim("Account", account),
            new Claim(ClaimTypes.Email, email),
        },
    DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(identity);

    return this.RedirectToAction("Index", "Home");
}

// 登入失敗,返回原登入頁面
return this.View(loginForm);