3分钟快速学会在ASP.NET Core MVC中如何使用Cookie

一.Cookie是什么?

我的朋友问我cookie是什么,用来干什么的,可是我居然无法清楚明白简短地向其阐述cookie,这不禁让我陷入了沉思:为什么我无法解释清楚,我对学习的方法产生了怀疑!所以我们在学习一个东西的时候,一定要做到知其然知其所以然。

HTTP协议本身是无状态的。什么是无状态呢,即服务器无法判断用户身份。Cookie实际上是一小段的文本信息)。客户端向服务器发起请求,如果服务器需要记录该用户状态,就使用response向客户端浏览器颁发一个Cookie。客户端浏览器会把Cookie保存起来。当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie一同提交给服务器。服务器检查该Cookie,以此来辨认用户状态。

打个比方,这就犹如你办理了银行卡,下次你去银行办业务,直接拿银行卡就行,不需要身份证。

二.在.NET Core中尝试

废话不多说,干就完了,现在我们创建ASP.NET Core MVC项目,撰写该文章时使用的.NET Core SDK 3.0 构建的项目,创建完毕之后我们无需安装任何包,

但是我们需要在Startup中添加一些配置,用于Cookie相关的。

//public const string CookieScheme = "YourSchemeName";
  public Startup(IConfiguration configuration)
  {
   Configuration = configuration;
  }
  public IConfiguration Configuration { get; }
  // This method gets called by the runtime. Use this method to add services to the container.
  public void ConfigureServices(IServiceCollection services)
  {
   //CookieAuthenticationDefaults.AuthenticationScheme Cookies Default Value
   //you can change scheme
   services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
     options.LoginPath = "/LoginOrSignOut/Index/";
    });
   services.AddControllersWithViews();
   // is able to also use other services.
   //services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, ConfigureMyCookie>();
  }

在其中我们配置登录页面,其中 AddAuthentication 中是我们的方案名称,这个是做什么的呢?很多小伙伴都懵懵懂懂表示很懵逼啊,我看很多人也是都写得默认,那它到底有啥用,经过我看AspNetCore源码发现它这个是可以做一些配置的。看下面的代码:

internal class ConfigureMyCookie : IConfigureNamedOptions<CookieAuthenticationOptions>
 {
  // You can inject services here
  public ConfigureMyCookie()
  {}
  public void Configure(string name, CookieAuthenticationOptions options)
  {
   // Only configure the schemes you want
   //if (name == Startup.CookieScheme)
   //{
    // options.LoginPath = "/someotherpath";
   //}
  }
  public void Configure(CookieAuthenticationOptions options)
   => Configure(Options.DefaultName, options);
 }

在其中你可以定义某些策略,随后你直接改变 CookieScheme 的变量就可以替换某些配置,在配置中一共有这几项,这无疑是帮助我们快速使用Cookie的好帮手~点个赞。

在源码中可以看到Cookie默认保存的时间是14天,这个时间我们可以去选择,支持TimeSpan的那些类型。

public CookieAuthenticationOptions()
  {
   ExpireTimeSpan = TimeSpan.FromDays(14);
   ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
   SlidingExpiration = true;
   Events = new CookieAuthenticationEvents();
  }

接下来LoginOrOut Controller,我们模拟了登录和退出,通过 SignInAsync 和 SignOutAsync 方法。

[HttpPost]
  public async Task<IActionResult> Login(LoginModel loginModel)
  {
   if (loginModel.Username == "haozi zhang" &&
    loginModel.Password == "123456")
   {
    var claims = new List<Claim>
     {
     new Claim(ClaimTypes.Name, loginModel.Username)
     };
    ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "login"));
    await HttpContext.SignInAsync(principal);
    //Just redirect to our index after logging in.
    return Redirect("/Home/Index");
   }
   return View("Index");
  }
  /// <summary>
  /// this action for web lagout
  /// </summary>
  [HttpGet]
  public IActionResult Logout()
  {
   Task.Run(async () =>
   {
    //注销登录的用户,相当于ASP.NET中的FormsAuthentication.SignOut
    await HttpContext.SignOutAsync();
   }).Wait();
   return View();
  }

就拿出推出的源码来看,其中获取了Handler的某些信息,随后将它转换为 IAuthenticationSignOutHandler 接口类型,这个接口 as 接口,像是在地方实现了这个接口,然后将某些运行时的值引用传递到该接口上。

public virtual async Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties)
  {
   if (scheme == null)
   {
    var defaultScheme = await Schemes.GetDefaultSignOutSchemeAsync();
    scheme = defaultScheme?.Name;
    if (scheme == null)
    {
     throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultSignOutScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).");
    }
   }
   var handler = await Handlers.GetHandlerAsync(context, scheme);
   if (handler == null)
   {
    throw await CreateMissingSignOutHandlerException(scheme);
   }
   var signOutHandler = handler as IAuthenticationSignOutHandler;
   if (signOutHandler == null)
   {
    throw await CreateMismatchedSignOutHandlerException(scheme, handler);
   }
   await signOutHandler.SignOutAsync(properties);
  }

其中 GetHandlerAsync 中根据认证策略创建了某些实例,这里不再多说,因为源码深不见底,我也说不太清楚...只是想表达一下看源码的好处和坏处....

public async Task<IAuthenticationHandler> GetHandlerAsync(HttpContext context, string authenticationScheme)
  {
   if (_handlerMap.ContainsKey(authenticationScheme))
   {
    return _handlerMap[authenticationScheme];
   }

   var scheme = await Schemes.GetSchemeAsync(authenticationScheme);
   if (scheme == null)
   {
    return null;
   }
   var handler = (context.RequestServices.GetService(scheme.HandlerType) ??
    ActivatorUtilities.CreateInstance(context.RequestServices, scheme.HandlerType))
    as IAuthenticationHandler;
   if (handler != null)
   {
    await handler.InitializeAsync(scheme, context);
    _handlerMap[authenticationScheme] = handler;
   }
   return handler;
  }

最后我们在页面上想要获取登录的信息,可以通过 HttpContext.User.Claims 中的签名信息获取。

@using Microsoft.AspNetCore.Authentication
<h2>HttpContext.User.Claims</h2>
<dl>
 @foreach (var claim in User.Claims)
 {
  <dt>@claim.Type</dt>
  <dd>@claim.Value</dd>
 }
</dl>
<h2>AuthenticationProperties</h2>
<dl>
 @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
 {
  <dt>@prop.Key</dt>
  <dd>@prop.Value</dd>
 }
</dl>

三.最后效果以及源码地址#

GitHub地址:https://github.com/zaranetCore/aspNetCore_JsonwebToken/tree/master/src/Identity.Cookie/DotNetCore_Cookie_Sample

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。

(0)

相关推荐

  • asp.net清空Cookie的两种方法

    asp.net清空Cookie的两种方法 第一种 Cookie.Expires=[DateTime]; Response.Cookies("UserName").Expires = 0; 第二种 Response.Cookies["admin"].Expires = DateTime.Now.AddDays(-1);

  • asp.net cookie的操作,写入、读取与操作

    写入: 复制代码 代码如下: HttpCookie cookie = new HttpCookie("id_admin_"); cookie.Value = model.id_admin_.ToString(); //cookie.Domain = ".sosuo8.com"; HttpContext.Current.Response.Cookies.Add(cookie); cookie = new HttpCookie("name_admin_&quo

  • asp.net cookie清除的代码

    Request.Cookies.Clear()这个方法并不是删除Cookie 删除 Cookie(即从用户的硬盘中物理移除 Cookie)是修改 Cookie 的一种形式. 由于 Cookie 在用户的计算机中,因此无法将其直接移除. 但是,可以让浏览器来为您删除 Cookie. 该技术是创建一个与要删除的 Cookie 同名的新 Cookie, 并将该 Cookie 的到期日期设置为早于当前日期的某个日期. 当浏览器检查 Cookie 的到期日期时,浏览器便会丢弃这个现已过期的 Cookie.

  • asp.net关于Cookie跨域(域名)的问题

    跨二级域名 我们知道cookie是可以跨二级域名来访问,这个很好理解,例如你 www.test1.com 在的web应用程序创建了一个cookie,要想在bbs.test1.com这样的二级域名对应的应用程序中访问,就必须你在创建cookie的时候设置domain参数domain=test1.com. 以asp.net为例 代码如下: 复制代码 代码如下: HttpCookie cookie = new HttpCookie("name", "www.Admin10000.c

  • asp.net Cookie值中文乱码问题解决方法

    cookie里面不能写中文,是由于cookie先天的编码方式造成的.所以需要有一种中间编码来过渡. URLEncode是最好的选择. 我们以asp.net为例,代码如下: 设置Cookie时: 复制代码 代码如下: HttpCookie cookie = new HttpCookie("name", System.Web.HttpContext.Current.Server.UrlEncode("我们")); Response.Cookies.Add(cookie)

  • asp.net Cookie跨域、虚拟目录等设置方法

    Cookie有三个属性需要注意一下: . Domain 域 . Path 路径 . Expires 过期时间 跨域操作需要设置域属性: Response.Cookies("MyCookie").Domain = "jb51.net"; (这里指的是泛域名) 这样在其它二级域名下就都可以访问到了, ASP 和 ASP.NET 测试通过 虚拟目录下访问: 我在ASP端做了下测试,.NET的没试, 如果不指定Path属性, 不同虚拟目录下Cookie无法共享 将Respo

  • asp.net利用cookie保存用户密码实现自动登录的方法

    本文实例讲述了asp.net利用cookie保存用户密码实现自动登录的方法.分享给大家供大家参考.具体分析如下: 在asp.net中可以用cookie保存用户的帐户密码实现自动登录的功能,但是需要强调一下,cookie在客户端保存,是不安全的,推荐使用md5加密保存. 下面分析一下在asp.net中cookie的创建.提取与销毁的方法: 创建cookie 复制代码 代码如下: //向客户端写入Cookie HttpCookie hcUserName1 = new HttpCookie("unam

  • asp.net中的cookie使用介绍

    一.cookie导读,理解什么是cookie 1.什么是cookie:cookie是一种能够让网站服务器把少量数据(4kb左右)存储到客户端的硬盘或内存.并且读可以取出来的一种技术. 2.当你浏览某网站时,由web服务器放置于你硬盘上的一个非常小的文本文件,它可以记录你的用户id.浏览过的网页或者停留的时间等网站想要你保存的信息.当你再次通过浏览器访问该网站时,浏览器会自动将属于该网站的cookie发送到服务器去,服务器通过读取cookie,得知你的相关信息,就可以做出相应的动作.比如,显示欢迎

  • asp.net(C#)跨域及跨域写Cookie问题

    解决方法是: 复制代码 代码如下: //www.B.com里的被调用的页面需要写P3P头,从而解除IE对写Cookie的阻止 context.Response.AddHeader("P3P", "CP=CAO PSA OUR"); //www.A.com里通过ajax调用www.B.com里的内容时,是跨域访问,需要使用jsonp,为配合其工作需要添加下面两句,生成jsonp返回 context.Response.ContentType = "text/p

  • ASP.NET之Response.Cookies.Remove 无法删除COOKIE的原因

    例子如下: 复制代码 代码如下: protected void Page_Load(object sender, EventArgs e){    if (!IsPostBack)    {        HttpCookie UserInfo = new HttpCookie("UserInfo");        UserInfo.Value = "bdstjk";        Response.Cookies.Add(UserInfo);    } } pr

随机推荐