码迷,mamicode.com
首页 > Web开发 > 详细

.net core mvc 简易登录

时间:2019-07-31 18:19:31      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:omd   tar   rect   ext   ica   cookie   res   startup   ati   

Startup.cs文件:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/Home/Login";
                    options.ExpireTimeSpan = TimeSpan.FromDays(2);
                });
//注意app.UseAuthentication方法一定要放在下面的app.UseMvc方法前面,否者后面就算调用HttpContext.SignInAsync进行用户登录后,使用
            //HttpContext.User还是会显示用户没有登录,并且HttpContext.User.Claims读取不到登录用户的任何信息。
            //这说明Asp.Net OWIN框架中MiddleWare的调用顺序会对系统功能产生很大的影响,各个MiddleWare的调用顺序一定不能反
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Pages}/{action=Applet}/{id?}");
            });

 

登录:

 [HttpPost]
        public async Task<IActionResult> Login(LoginModel dto)
        {
            //登陆授权
            if (dto.UserName == "admin" && dto.Password == "siia")
            {
                var claims = new List<Claim>(){
                new Claim(ClaimTypes.Name,dto.UserName),
                new Claim(ClaimTypes.Role,"admin")
            };
                var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity));
                //验证是否授权成功
                //if (User.Identity.IsAuthenticated)
                //{
                //    return RedirectToPage("Index");
                //}
                return RedirectToAction("Applet", "Pages");
            }
            else
            {
                ViewBag.msg = "账号密码错误";
                return View();
            }

        }
        public async Task<IActionResult> Logout()
        {
            //TODO:注销处理
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login");
        }

 

.net core mvc 简易登录

标签:omd   tar   rect   ext   ica   cookie   res   startup   ati   

原文地址:https://www.cnblogs.com/SmilePastaLi/p/11277881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!