Search code examples
asp.net-coreauthenticationcookiesasp.net-identityidentity

What is difference between these two cookie configurations for cookie-based authentication?


What is difference between these two cookie configurations for cookie-based authentication?

Variant 1

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // Configure cookie based authentication:
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(opt =>
            {
                /* validation rules */    
            });
}

Variant 2

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<AppUser, AppRole>(opt =>
    {
        /* validation rules */
    });

    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = new PathString("/User/Login");

        options.Cookie = new CookieBuilder
        {
            Name = "AspNetCoreIdentityExampleCookie",
            HttpOnly = false,
            SameSite = SameSiteMode.Lax,
            SecurePolicy = CookieSecurePolicy.Always
        };

        options.ExpireTimeSpan = TimeSpan.FromMinutes(2);
        options.SlidingExpiration = true;
    });
}

I can't understand the difference, I will be glad for hearing any help.


Solution

  • Variant one involves configuring cookie-based authentication manually, without utilizing the provided Identity framework. On the other hand, Variant two involves calling AddIdentity, which automatically adds cookie-based authentication and allows for customization of the configuration using ConfigureApplicationCookie.

    Reference.