Search code examples
c#asp.net-coreasp.net-core-identity

Get ASP.NET Core Identity auth cookie name


During startup, I configure the Identity auth cookie:

services.ConfigureApplicationCookie(x =>
{
  x.Cookie.Name = "foo";    // default is ".AspNetCore.Identity.Application"
  // other config...
});

I need that cookie's info during runtime, so in some controller I inject IOptions<CookieAuthenticationOptions>, and then try get the cookie name:

var cookieName = cookieAuthenticationOptions.Value.Cookie;

That gives ".AspNetCore." instead of "foo". That object's other properties are also wrong, they all seem to be default values.

Why is this happening, and how do I get a valid instance of that options object?


Solution

  • ASP.NET Core Identity uses a named IOptions approach, but the default IOptions DI provides a default, unnamed instance of (in this case) CookieAuthenticationOptions. That means the instance you get from DI is different to the one configured using ConfigureApplicationCookie.

    To access a named instance of IOptions, you can use either IOptionsSnapshot or IOptionsMonitor (docs). Here's an example of how to access the ASP.NET Core Identity instance of CookieAuthenticationOptions:

    1. Inject IOptionsMonitor<CookieAuthenticationOptions> into the controller's constructor.

    2. In the action, use the following code:

      var cookieName = cookieAuthenticationOptions
         .Get(IdentityConstants.ApplicationScheme)
         .Cookie.Name;