Net Core教程

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

这篇关于asp.net core cookie身份验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!