(精华)2020年8月18日 ASP.NET Core 添加cookie的方式进行授权,鉴权

164 阅读1分钟
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = new PathString("/Fourth/Login");//没有登入会跳转到这个地址
            options.AccessDeniedPath = new PathString("/Home/Privacy");
        });//用cookie的方式验证,顺便初始化登录地址
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
	app.UseAuthentication();//鉴权,检测有没有登录,登录的是谁,赋值给User
    app.UseAuthorization();//就是授权,检测权限
}

控制器中的使用

登录时添加用户缓存

[HttpPost]
public ActionResult Login(string name, string password, string verify)
{
    string verifyCode = base.HttpContext.Session.GetString("CheckCode");
    if (verifyCode != null && verifyCode.Equals(verify, StringComparison.CurrentCultureIgnoreCase))
    {
        if ("天才".Equals(name) && "123456".Equals(password))
        {
            CurrentUser currentUser = new CurrentUser()
            {
                Id = 123,
                Name = "天才",
                Account = "Administrator",
                Email = "57265177",
                Password = "123456",
                LoginTime = DateTime.Now
            };
            #region Cookie/Session 自己写
            //base.HttpContext.SetCookies("CurrentUser", Newtonsoft.Json.JsonConvert.SerializeObject(currentUser), 30);
            //base.HttpContext.Session.SetString("CurrentUser", Newtonsoft.Json.JsonConvert.SerializeObject(currentUser));
            #endregion
            //过期时间全局设置

            #region MyRegion
            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Name,name),
                new Claim("password",password),//可以写入任意数据
                new Claim("Account","Administrator")
            };
            var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
            }).Wait();//没用await
            //cookie策略--用户信息---过期时间
            #endregion

            return base.Redirect("/Home/Index");
        }
        else
        {
            base.ViewBag.Msg = "账号密码错误";
        }
    }
    else
    {
        base.ViewBag.Msg = "验证码错误";
    }
    return View();
}

[HttpPost]
public ActionResult Logout()
{
    #region Cookie
    base.HttpContext.Response.Cookies.Delete("CurrentUser");
    #endregion Cookie

    #region Session
    CurrentUser sessionUser = base.HttpContext.GetCurrentUserBySession();
    if (sessionUser != null)
    {
        this._logger.LogDebug(string.Format("用户id={0} Name={1}退出系统", sessionUser.Id, sessionUser.Name));
    }
    base.HttpContext.Session.Remove("CurrentUser");
    base.HttpContext.Session.Clear();
    #endregion Session

    #region MyRegion
    //HttpContext.User.Claims//其他信息
    HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).Wait();
    #endregion
    return RedirectToAction("Index", "Home"); ;
}

获取用户信息

CurrentUser currentUser = base.Context.User.Identity.Name == null ? null : new CurrentUser()

用户认证在控制器或方法加上如下特性

[Authorize]