Implement a secure Blazor Web application using OpenID Connect and security headers
https://github.com/dotnet/blazor-samples/tree/main/8.0/BlazorWebAppOidc
Set this as the used OIDC client recommends. If using the default, something like this:
builder.Services.AddAuthentication(OIDC_SCHEME)
.AddOpenIdConnect(OIDC_SCHEME, options =>
{
// From appsettings.json, keyvault, user-secrets
builder.Configuration.GetSection("OpenIDConnectSettings").Bind(options);
})
.AddCookie();
Note: Each identity provider uses different OIDC configurations and events.
Blazor Web WASM does not support CSP nonces. If you require this, then you need to disable security features.
Switch to server components:
In the Program.cs, switch
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
to
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
In the Program.cs, switch
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(Counter).Assembly);
to
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddAdditionalAssemblies(typeof(Counter).Assembly);
In App.razor:
<HeadOutlet @rendermode="InteractiveAuto" />
</head>
<body>
<Routes @rendermode="InteractiveAuto" />
to
<HeadOutlet @rendermode="InteractiveServer" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
Blazor Web WASM does not support CSP nonces. If you require this, then you need to disable security features.
builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped<CircuitHandler, BlazorNonceService>(sp =>
sp.GetRequiredService<BlazorNonceService>()));
builder.Services.AddScoped<BlazorNonceService>();
app.UseMiddleware<NonceMiddleware>();
Nonce services are in the CspServices folder in the BlazorWebAppOidc project.
Security headers can reduce the attack surface in the application. This is applied as best possible for the tech stack requirements.
app.UseSecurityHeaders(
SecurityHeadersDefinitions.GetHeaderPolicyCollection(
app.Environment.IsDevelopment(),
app.Configuration["OpenIDConnectSettings:Authority"]));
See SecurityHeadersDefinitions.cs
- 2024-10-06 Updated packages, update security headers
- 2024-08-14 Updated packages
- 2024-06-30 Updated packages
- 2024-05-26 Updated packages
https://github.com/dotnet/blazor-samples/tree/main/8.0/BlazorWebAppOidc
https://damienbod.com/2024/02/19/using-a-csp-nonce-in-blazor-web/