CookieAuthenticationHandler±ãÊÇCookieÈÏÖ¤µÄ¾ßÌåʵÏÖ£º
public class CookieAuthenticationHandler : AuthenticationHandler<CookieAuthenticationOptions>, IAuthenticationSignInHandler, IAuthenticationSignOutHandler { ... protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { var result = await EnsureCookieTicket(); if (!result.Succeeded) { return result; } var context = new CookieValidatePrincipalContext(Context, Scheme, Options, result.Ticket); // Ö´ÐÐÇ°¶ø½éÉܵķþÎñ¶ËÑéÖ¤ await Events.ValidatePrincipal(context); if (context.ShouldRenew) { // ÖØÐÂÉú³ÉCookie RequestRefresh(result.Ticket); } return AuthenticateResult.Success(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); } public async virtual Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) { ... var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.Scheme.Name); .... var cookieValue = Options.TicketDataFormat.Protect(ticket, GetTlsTokenBinding()); Options.CookieManager.AppendResponseCookie(Context, Options.Cookie.Name, cookieValue, signInContext.CookieOptions); var signedInContext = new CookieSignedInContext(Context, Scheme, signInContext.Principal, signInContext.Properties, Options); await Events.SignedIn(signedInContext); var shouldRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath; await ApplyHeaders(shouldRedirect, signedInContext.Properties); Logger.SignedIn(Scheme.Name); } }ÆäºËÐÄ·½·¨HandleAuthenticateAsync»á¼ì²éÇëÇóCookie£¬²éÕÒÓëCookieBuilder.Name¶ÔÓ¦µÄCookieÖµ£¬½âÃÜ·´ÐòÁл¯³ÉAuthenticationTicket¶ÔÏó£¬×îºóÔÚÉÏÒ»Õ½éÉܵÄÖмä¼þÖн«Principal¸³Óè¸øHttpContext¡£
¶øCookieAuthenticationHandler»¹ÊµÏÖÁËIAuthenticationSignInHandlerºÍIAuthenticationSignOutHandler£¬ÕâÒ²ÊÇASP.NET CoreÖÐÄÚÖõÄΨһ֧³ÖµÇ¼ºÍÍ˳öµÄÈÏÖ¤·½Ê½¡£ÔÚSignInAsync·½·¨ÖÐʹÓÃClaimsPrincipalÀ´´´½¨Ò»¸öAuthenticationTicket¶ÔÏó£¬È»ºó½«Æä¼ÓÃÜ£¬Ð´Èëµ½CookieÖУ¬±ãÍê³ÉÁ˵Ǽ£¨Éí·ÝÁîÅƵķ¢·Å£©£¬¶øSignOutAsync·½·¨ÔòÖ»ÊǼòµ¥µÄɾ³ýCookie¡£
ƪ·ùÓÐÏÞ£¬¾Í²»ÔÙ¶à˵£¬¸ÐÐËȤµÄ¿ÉÒÔÈ¥¿´Ò»ÏÂÍêÕû´úÂ룺CookieAuthenticationHandler¡£
×ܽáCookieÈÏÖ¤ÊÇÒ»ÖÖ±¾µØÈÏÖ¤·½Ê½£¬Ò²ÊÇ×îΪ¼òµ¥£¬×îΪ³£ÓõÄÈÏÖ¤·½Ê½¡£ÆäÈÏÖ¤Âß¼Ò²ºÜ¼òµ¥£¬×ܽáһϾÍÊÇ»ñÈ¡ÇëÇóÖÐÖ¸¶¨µÄCookie£¬½âÃܳɹ¦ºó£¬·´ÐòÁÐÉú³É AuthenticationTicket ¶ÔÏ󣬲¢½øÐÐһϵÁеÄÑéÖ¤£¬¶øµÇ¼·½·¨ÓëÖ®¶ÔÓ¦£º¸ù¾ÝÓû§ÐÅÏ¢´´½¨ AuthenticationTicket ¶ÔÏ󣬲¢¼ÓÃܺóÐòÁл¯£¬Ð´Èëµ½CookieÖС£ÔÚÏÂÒ»ÕÂÖУ¬¾ÍÀ´½éÉÜÒ»ÏÂ×îΪÁ÷ÐеÄÔ¶³ÌÈÏÖ¤·½Ê½£ºOAuth ºÍ OpenID Connect¡£
×îºó¸½Éϱ¾ÎÄÖеÄʾÀý´úÂ룺https://github.com/RainingNight/AspNetCoreSample/tree/master/src/CookieSample¡£
posted @
¡¡