1. 程式人生 > 其它 >asp.net core cookie身份驗證

asp.net core cookie身份驗證

1、建立一個帶有mvc的asp.net core 應用程式,本文例項選擇的版本是.net 5。(文末有完整demo)

2、startup中的ConfigureServices和Configure分別增加核心驗證程式碼

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options 
=> { //cookie認證更多配置 options.Cookie.Name = "AuthCookie";//cookie名稱 options.LoginPath = "/User/Login";//登入路徑 options.Cookie.HttpOnly = true;//cookie操作許可權 }); services.AddControllersWithViews(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //驗證你是誰,注意順序,要放到UseAuthorization之前 app.UseAuthentication(); //是否允許訪問 app.UseAuthorization(); app.UseEndpoints(endpoints
=> { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }

3、新增UserController.cs核心驗證程式碼

    public class UserController : Controller
    {
        private UserStore _userStore;
        private IHttpContextAccessor _httpcontext;
        public UserController(UserStore userStore, IHttpContextAccessor httpContextAccessor)
        {
            _userStore = userStore;
            _httpcontext = httpContextAccessor;
        }
        /// <summary>
        /// 使用者首頁
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            var IsAuthenticated = _httpcontext.HttpContext.User?.Identity?.IsAuthenticated ?? false;
            if (IsAuthenticated)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append($"當前登入使用者:{_httpcontext.HttpContext.User.Identity.Name}<br/>");
                sb.Append($"驗證型別:{_httpcontext.HttpContext.User.Identity.AuthenticationType}<br/>");
                foreach (var item in _httpcontext.HttpContext.User.Claims)
                {
                    sb.Append($"{item.Type}-{item.Value}<br/>");
                }
                ViewBag.UserMessage = sb.ToString();
            }
            ViewBag.IsAuthenticated = IsAuthenticated;
            return View();
        }
        /// <summary>
        /// 登入頁
        /// </summary>
        /// <param name="ErrorMessage"></param>
        /// <returns></returns>
        public IActionResult Login(string ErrorMessage)
        {
            ViewBag.ErrorMessage = ErrorMessage;
            return View();
        }
        /// <summary>
        /// 登入驗證
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(string Name, string Password)
        {
            var user = _userStore.FindUser(Name, Password);
            if (user == null)
            {
                return RedirectToAction("Login", new { ErrorMessage = "使用者名稱密碼不正確" });
            }
            else
            {
                var claimIdentity = new ClaimsIdentity("Cookie");
                claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
                claimIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
                claimIdentity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
                claimIdentity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber));
                claimIdentity.AddClaim(new Claim(ClaimTypes.DateOfBirth, user.Birthday.ToString()));

                var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
                HttpContext.SignInAsync(claimsPrincipal);
                return RedirectToAction("Index");
            }
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public IActionResult Logout()
        {
            HttpContext.SignOutAsync();
            return Redirect("Index");
        }
    }

4、身份驗證:HomeController中找個action測試身份驗證。[Authorize]特性限制訪問未經授權的請求的資料/資訊,並重定向到登入頁面以檢查使用者是否有效。

  

/// <summary>
        /// 新增身份驗證
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Privacy()
        {
            return View();
        }

5、完整demo:https://gitee.com/xiaoqingyao/authentication-cookie.git

源:https://www.cnblogs.com/RainingNight/p/cookie-authentication-in-asp-net-core.html