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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章