asp.net core3.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();//就是授权,检测权限
}

控制器中的使用

添加用户缓存

#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

获取用户信息

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

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

[Authorize]

三种方式的登入

[HttpPost]
        //[CustomAllowAnonymous]
        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 ("Eleven".Equals(name) && "123456".Equals(password))
                {
                    CurrentUser currentUser = new CurrentUser()
                    {
                        Id = 123,
                        Name = "XT",
                        Account = "Administrator",
                        Email = "111111",
                        Password = "222222",
                        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]
        //[CustomAllowAnonymous]
        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"); ;
        }

你可能感兴趣的:(.NET,Core3.1实战专题)