.net core 登录验证

发布时间:2022-06-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了.net core 登录验证脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

功能:登录后,才能访问后续页面。

否则跳转到登录页

 

一,startup

public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();
            services.AddControllersWithViews();
            //添加 身份验证 服务
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
            AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
                {
                    o.LoginPath = new PathString("/Home/Login");// 登录页面的url
                    o.AccessDeniedPath = new PathString("/Login");//没有授权跳转的页面
                    o.ExpireTimeSpan = TimeSpan.FromHours(0.5); // cookies的过期时间
                });
        }

 

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
 
            app.UseAuthentication();        //登录验证,要放在UseAuthorization之前!
            app.UseAuthorization();
           
        }

 

二,登录功能

Login是登录页

LoginAction是登录按钮触发的方法

LogoutAction是注销

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
 
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
 
        public IActionResult Login()
        {
            return View();
        }
 
        public IActionResult LoginAction(UserVO entity)
        {
            ClaimsIdentity identity = new ClaimsIdentity("Forms");
            identity.AddClaim(new Claim(ClaimTypes.Sid, entity.account));
            identity.AddClaim(new Claim(ClaimTypes.Name, entity.pwd));
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
 
            return RedirectToAction("Index", "Email");
        }
        public IActionResult LogoutAction()
        {
            HttpContext.SignOutAsync().Wait();
            return RedirectToAction("Login", "Home");
        }
 
    }

 

跳转页 --  [Authorize]  代表需要验证,

直接访问时,看看是不是会返回登录页

[Authorize]
    public class EmailController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

 

脚本宝典总结

以上是脚本宝典为你收集整理的.net core 登录验证全部内容,希望文章能够帮你解决.net core 登录验证所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: