΢ Ͷ ^ ھ

cba上海男篮赛程 :3犿ٌWASP.NET Core MVCʹCookie

cba㶫 www.axwwg.com  •rg2020-01-25 00:02:18   ߣ   ҪuՓ(0)

һ.Cookieʲô


ҵцcookieʲôÁʲôҾȻo׺̵Ucookie@׌˳˼ʲôҟoҌ

һ.Cookieʲô

ҵцcookieʲôÁʲôҾȻo׺̵Ucookie@׌˳˼ʲôҟoҌWķaˑ҂ڌWһ|ĕrһҪ֪Ȼ֪Ȼ

HTTPfhǟoBʲôǟoBoДÑCookieHһСεıϢ?ͻAl?ҪӛԓÑBʹresponse͑˞g[ClһCookie?ͻmCookieg[ՈԓWվrg[ՈľWַBͬԓCookieһͬύozԓCookieԴˁJÑB

򂀱ȷ@ͪqkyп´ȥykIֱyпҪC

..NET CoreЇLԇ

UԒfɾF҂ASP.NET Core MVCĿ׫ԓ•rʹõ.NET Core SDK 3.0 Ŀꮅ֮҂o谲bκΰ

҂ҪStartupһЩCookieP

//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 ҂ķQ@ʲôܶС鶼¶ʾ±ưҿܶҲǶĬJɶ^ҿAspNetCoreԴalF@ǿһЩõ?”ËĴ?/p>

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

ԶxijЩSֱӸ׃ CookieScheme ׃ͿQijЩһ@@oǎ҂ʹCookieĺÎ~cٝ


ԴaпԿCookieĬJĕrg14@rg҂ȥx֧TimeSpanЩ

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

LoginOrOut Controller҂ģM˵䛺˳ͨ^ 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 () =>
   {
    //עN䛵ÑஔASP.NETеFormsAuthentication.SignOut 
    await HttpContext.SignOutAsync();
   }).Wait();
   return View();
  }

óƳԴaЫ@ȡHandlerijЩϢSDQ IAuthenticationSignOutHandler ӿ@ӿ as ӿڵطF@ӿȻijЩ\ЕrֵÂfԓӿ

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 иJCԄijЩ@ﲻٶfԴaҊҲf̫...ֻ_һ¿Դaĺ͉̎̎....

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>

.ЧԼԴaַ#


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

Y

Ͼ@ƪµȫϣĵă݌ҵČW߹һąWrֵxxҌ_֮ҵ֧

ܸdȤ:

  • asp.net cookieIJxȡc
  • ASP.NET֮Response.Cookies.Remove ohCOOKIEԭ
  • asp.netCookieăɷN
  • asp.net Cookie̓MĿ䛵O÷
  • asp.net(C#)򼰿Cookie}
  • asp.net Cookieֵāya}Q
  • asp.netcookieÑܴaFԄӵ䛵ķ
  • asp.netPCookieĆ}
  • asp.netеcookieʹýB
  • asp.net cookieĴa

P