Asp.net Core3.1 Cookie认证 简单使用

3 篇文章 0 订阅
3 篇文章 0 订阅

1、网上很多相关的文章来解释【认证】,以下是摘取网上看到的对【认证】的理解

一般来说,术语认证指的是任何验证某人(无论是人还是自动系统)是其声称的人(或什么)的过程。在万维网WWW的上下文中也是如此,该词主要用于表示网站或服务使用的任何技术,以从用户代理(通常是 Web 浏览器)收集一组登录信息,并使用成员资格和/或身份服务对其进行身份验证。

身份验证是确定用户身份的过程。 授权是确定用户是否有权访问资源的过程。 在 ASP.NET Core 中,身份验证由 IAuthenticationService 负责,而它供身份验证中间件使用。 身份验证服务会使用已注册的身份验证处理程序来完成与身份验证相关的操作。

2、本文简单记录一下使用Cookie认证

2.1、添加服务

   services.AddAuthentication((option) =>
            {
                //设置默认项
                option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option => {
                option.Cookie.Name = "adCookie";//设置存储用户登录信息(用户Token信息)的Cookie名称
                option.Cookie.HttpOnly = true;//设置存储用户登录信息(用户Token信息)的Cookie,无法通过客户端浏览器脚本(如JavaScript等)访问到
                option.ExpireTimeSpan = TimeSpan.FromDays(3);// 过期时间
                option.SlidingExpiration = true;// 是否在过期时间过半的时候,自动延期
                option.LoginPath = "/Home/Login";
                option.LogoutPath = "/Home/LogOut";
            });

2.2、添加中间件
         

      app.UseAuthentication();

        中间件要放到  app.UseRouting();     app.UseEndpoints() 之间

       通过调用 UseAuthentication,在 Startup.Configure 中添加身份验证中间件。 如果调用 UseAuthentication,会注册使用之前注册的身份验证方案的中间件。 请在依赖于要进行身份验证的用户的所有中间件之前调用 UseAuthentication。 如果使用终结点路由,则必须按以下顺序调用 UseAuthentication

  • 在 UseRouting之后调用,以便路由信息可用于身份验证决策。
  • 在 UseEndpoints 之前调用,以便用户在经过身份验证后才能访问终结点。

2.3、创建初始Web项目,选择默认Asp.net Core Web 应用

        添加用户信息类:

 public class User
    {
        public int ID { get; set; }
        public string username { get; set; }

        public string pwd { get; set; }

    }

        添加返回信息类:

        

    public class ReturnResult
    {
        public int Result { get; set; }


        public string Msg { get; set; }

    }

在Home控制器下添加 登录和登出方法  Login  Logout

添加Login 方法

 [HttpPost]
        public async Task<ReturnResult> Login(string username, string pwd)
        {
            ReturnResult returnResult = new ReturnResult();

            var user = new UserBLL().GetUser(username, pwd);

            if (user == null)
            {
                returnResult.Result = -1;
                returnResult.Msg = "用户名或密码错误";
            }
            else
            {
                var claims = new List<Claim> {
                     new Claim("userName",username),
                     new Claim("userID",user.ID.ToString())
                    };
                await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme))); //Cookie 验证
                returnResult.Result = 0;
                returnResult.Msg = "登录成功";
            }

            return returnResult;
        }

添加LogOut

    public async void LogOut()
        { 
            await HttpContext.SignOutAsync();
            HttpContext.Response.Redirect("/");
        }

页面添加登录:

    <form action="/Home/Login" method="post" >

        <input id="username" name="username" type="text" />
        <input id="pwd" name="pwd" type="password" /> 
        <input type="submit"  value="登录" />
    </form>

添加获取数据类:

随便写一个返回用户信息的方法

    public class UserBLL
    {
        public User GetUser(string username, string pwd)
        {
            return new User() { ID=1, username = username, pwd = pwd };
        }
    }

在Privacy方法中添加以下代码用来查看是否经过Cookie认证

        public IActionResult Privacy()
        {
            if (HttpContext.User!=null && HttpContext.User.Claims.Count() > 0)
            {
                string claims = "";
                foreach (var item in HttpContext.User.Claims)
                {
                    claims+=$"Type:{item.Type } Value:{item.Value} ";
                }

                return Json(claims);
            }
            return View();
        }

2.5、启动项目

 

 登录后

浏览器查看:

访问 Home/Privacy 

浏览器查看请求标头增加Cookie

登出 Home/LogOut  返回首页

点击Privacy,或者访问Home/Privacy

 请求的标头 少了adCookie

参考文章:ASP.NET Core 身份验证概述 | Microsoft Learn

ASP.NET Core 认证与授权[2]:Cookie认证 - 雨夜朦胧 - 博客园

asp.net core 3.1多种身份验证方案,cookie和jwt混合认证授权 - XSpringSun - 博客园

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ShanShanYouWen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值