Asp.Net Core 6 之基於Cookie 的身份驗證


配置身份驗證

Program.cs


    //選擇使用那種方式來身份驗證
    builder.Services.AddAuthentication(option =>
    {
        option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; //默認身份驗證方案
        option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        option.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        option.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>
    {
        option.LoginPath = "/Account/Login";//如果沒有找到用戶信息---身份驗證失敗--授權也失敗了---就跳轉到指定的Action
        option.AccessDeniedPath = "/Home/NoAuthority";
    });


app.UseRouting();

app.UseAuthentication();//身份驗證中間件
app.UseAuthorization(); //授權中間件

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

登錄

AccountController.cs

public class AccountController : Controller
{
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(string useName, string password)
        {
            if ("admin".Equals(useName) && "123456".Equals(password))
            {
                var claims = new List<Claim>()//身份驗證信息
                    {
                        new Claim(ClaimTypes.Name,$"{useName}"),

                        new Claim("Userid","1"),
                        new Claim(ClaimTypes.Role,"Admin"),
                        new Claim(ClaimTypes.Role,"User"), 
                        new Claim(ClaimTypes.Email,$"xxx@163.com"),
                        new Claim("password",password),//可以寫入任意數據
                        new Claim("Account","Administrator"),
                        new Claim("role","admin"),
                         new Claim("QQ","xxx")
                    };

                ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(30),//過期時間:30分鍾

                }).Wait();
                var user = HttpContext.User;
                return base.Redirect("/Fourth/Index");
            }
            else
            {
                base.ViewBag.Msg = "用戶或密碼錯誤";
            }
            return await Task.FromResult<IActionResult>(View());
        }

}

重點:

                ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(30),//過期時間:30分鍾

                }).Wait();

檢查用戶和密碼正確后,根據當前用戶信息(比如:從數據庫查詢),創建ClaimsPrincipal 的實例對象,
然后為身份驗證方案CookieAuthenticationDefaults.AuthenticationScheme 執行登錄。

HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties(){....}

其中:CookieAuthenticationDefaults.AuthenticationScheme是身份驗證方案名

登出

HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme)

授權的使用

public XXXController:Controller
.....
       [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]  
       public IActionResult Xxx()
        {
            return View();
        }

因為以下代碼

    builder.Services.AddAuthentication(option =>
    {
        //設置默認身份驗證方案
        option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        ....
    }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>

設置了默認的身份驗證方案(名)是CookieAuthenticationDefaults.AuthenticationScheme;

可省略方案名

.....
       [Authorize]  
       public IActionResult Xxx()
        {
            return View();
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM