.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<IActionResult> 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, "MyEmail@qq.com"));
            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 = $"鉴权认证失败,用户未登录" });
        }
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuanlongWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值