ASP.NET Core 認証 Cookie の有効期限

プログラミング
公開: 2024年08月30日

目次

参考

ASP.NET Core Identity を使用せずに cookie 認証を使用する

実装

// Program.cs

// 認証処理(Cookie を使用)
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Login";
        options.AccessDeniedPath = "/AccessDenied";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
    });

この場合、Cookie そのものの有効期限は「セッション」に設定される。

Imgur

Cookie の有効期限を設定したい場合は、以下のように SignInAsync 時 に AuthenticationProperties の IsPersistent プロパティを true に設定する必要がある。

// Cookie にログイン情報を設定
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties
    {
        IsPersistent = true
    });

Imgur