溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在ASP.NET Core MVC中使用Cookie的方法

發(fā)布時(shí)間:2021-02-02 10:21:24 來源:億速云 閱讀:420 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了在ASP.NET Core MVC中使用Cookie的方法,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

一.Cookie是什么?

我的朋友問我cookie是什么,用來干什么的,可是我居然無法清楚明白簡(jiǎn)短地向其闡述cookie,這不禁讓我陷入了沉思:為什么我無法解釋清楚,我對(duì)學(xué)習(xí)的方法產(chǎn)生了懷疑!所以我們?cè)趯W(xué)習(xí)一個(gè)東西的時(shí)候,一定要做到知其然知其所以然。

HTTP協(xié)議本身是無狀態(tài)的。什么是無狀態(tài)呢,即服務(wù)器無法判斷用戶身份。Cookie實(shí)際上是一小段的文本信息)。客戶端向服務(wù)器發(fā)起請(qǐng)求,如果服務(wù)器需要記錄該用戶狀態(tài),就使用response向客戶端瀏覽器頒發(fā)一個(gè)Cookie??蛻舳藶g覽器會(huì)把Cookie保存起來。當(dāng)瀏覽器再請(qǐng)求該網(wǎng)站時(shí),瀏覽器把請(qǐng)求的網(wǎng)址連同該Cookie一同提交給服務(wù)器。服務(wù)器檢查該Cookie,以此來辨認(rèn)用戶狀態(tài)。

打個(gè)比方,這就猶如你辦理了銀行卡,下次你去銀行辦業(yè)務(wù),直接拿銀行卡就行,不需要身份證。

二.在.NET Core中嘗試

廢話不多說,干就完了,現(xiàn)在我們創(chuàng)建ASP.NET Core MVC項(xiàng)目,撰寫該文章時(shí)使用的.NET Core SDK 3.0 構(gòu)建的項(xiàng)目,創(chuàng)建完畢之后我們無需安裝任何包,

但是我們需要在Startup中添加一些配置,用于Cookie相關(guān)的。

//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 中是我們的方案名稱,這個(gè)是做什么的呢?很多小伙伴都懵懵懂懂表示很懵逼啊,我看很多人也是都寫得默認(rèn),那它到底有啥用,經(jīng)過我看AspNetCore源碼發(fā)現(xiàn)它這個(gè)是可以做一些配置的。看下面的代碼:

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 的變量就可以替換某些配置,在配置中一共有這幾項(xiàng),這無疑是幫助我們快速使用Cookie的好幫手~點(diǎn)個(gè)贊。

在ASP.NET Core MVC中使用Cookie的方法

在源碼中可以看到Cookie默認(rèn)保存的時(shí)間是14天,這個(gè)時(shí)間我們可以去選擇,支持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 () =>
   {
    //注銷登錄的用戶,相當(dāng)于ASP.NET中的FormsAuthentication.SignOut 
    await HttpContext.SignOutAsync();
   }).Wait();
   return View();
  }

就拿出推出的源碼來看,其中獲取了Handler的某些信息,隨后將它轉(zhuǎn)換為 IAuthenticationSignOutHandler 接口類型,這個(gè)接口 as 接口,像是在地方實(shí)現(xiàn)了這個(gè)接口,然后將某些運(yùn)行時(shí)的值引用傳遞到該接口上。

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 中根據(jù)認(rèn)證策略創(chuàng)建了某些實(shí)例,這里不再多說,因?yàn)樵创a深不見底,我也說不太清楚...只是想表達(dá)一下看源碼的好處和壞處....

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;
  }

最后我們?cè)陧撁嫔舷胍@取登錄的信息,可以通過 HttpContext.User.Claims 中的簽名信息獲取。

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

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

在ASP.NET Core MVC中使用Cookie的方法

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

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“在ASP.NET Core MVC中使用Cookie的方法”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI