.NET Core中鉴权 Authentication Authorization

  • Authentication: 鉴定身份信息,例如用户有没有登录,用户基本信息

  • Authorization: 判定用户有没有权限

使用框架提供的Cookie鉴权方式

1.首先在服务容器注入鉴权服务和Cookie服务支持

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;//不能少
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "Cookie/Login";
})
.AddCookie(options =>{});

2.注册鉴权和授权中间件,用于在管道中调用拦截校验鉴权和授权

app.UseAuthentication();
app.UseAuthorization();         

3.在控制器引入特性 [Authorize] ,调用登录接口时使用HttpContext.SignInAsync()写入鉴权信息

        [AllowAnonymous]
        [HttpPost]
        public async Task LoginAsync(string name, string password)
        {
            //用户名密码不正确直接返回
            if (!"Admin".Equals(name) || !"123456".Equals(password))
            {
                return new JsonResult(new { Result = false, Message = "登录失败" });
            }

            var claimIdentity = new ClaimsIdentity("Cookie");
            claimIdentity.AddClaim(new Claim(ClaimTypes.Name, name));
            claimIdentity.AddClaim(new Claim(ClaimTypes.Email, "[email protected]"));
            claimIdentity.AddClaim(new Claim(ClaimTypes.System, "EmployeeManager"));

            var Properties = new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
            };

            //写入鉴权信息
            await base.HttpContext.SignInAsync(new ClaimsPrincipal(claimIdentity), Properties);
            return new JsonResult(new { Result = true, Message = "登录成功" });
        }

4.因为调用 HttpContext.AuthenticateAsync() 获取鉴权的步骤,由第二部注册的中间件AuthenticationMiddleware已经替我们完成,所以可以直接在控制器内部获取HttpContext.User信息,系统提供的相对于自己实现的,框架帮我们封装了获取鉴权信息,并把它加入管道中,而不用每次在控制器中手动获取鉴权信息。

        [HttpGet]
        public IActionResult Authentication()
        {
            //这里由中间件管道已经实现了鉴权信息取值
            var CookiesInfo = base.HttpContext.User;
            if (CookiesInfo != null)
            {
                return new JsonResult(new { Result = true, Message = $"鉴权认证成功,用户已登录" });
            }
            return new JsonResult(new { Result = true, Message = $"鉴权认证失败,用户未登录" });
        }

你可能感兴趣的:(c#,.netcore)