Search code examples
.net-coreblazor.net-6.0blazor-server-side

Setting cookie expiration in Blazor server app using Azure AD for authentication


I created a simple .NET 6 Blazor Server app and followed some tutorials to add authenticate through Azure AD. Everything works fine, but when using the application hours later after it sitting idle I was not asked to login again. I noticed that the .AspNetCore.Cookies that gets set has Session expiration, so am guessing I'd need to close the browser, but I'd rather have a set expiration time if idle. Is that something that would be setup in Azure AD or in the application code?

My App.razor XML is wrapped with <CascadingAuthenticationState>. My appsettings.json has the AzureAd config. Here's the code being used in my Program.cs (mostly just defaults from creating new project and added auth code from tutorials):

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

Solution

  • I found the answer here: What is the correct way to set a cookie expiration when using Azure AD to login users to an ASP.NET Core 5 Web Application?

    I only needed to make a minor modification, instead of this.Configuration.GetSection("AzureAD").Bind(options), I used builder.Configuration.GetSection("AzureAD").Bind(options).

    It's also worth mentioning that it does NOT change the cookie expiration, it continued to be a session cookie, but I guess somewhere in the application the session does expire and it will go back to Azure AD for authentication.