Blazor進階: Share authentication cookies for SSO
在 ASP.NET 應用程式中共用驗證 cookie, Share authentication cookies among ASP.NET apps, SSO.
Last updated
在 ASP.NET 應用程式中共用驗證 cookie, Share authentication cookies among ASP.NET apps, SSO.
Last updated
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
IConfiguration config = builder.Configuration;
//# 與 ASP.NET Core 共用驗證 cookieIdentity
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"C:\Secure\SharedCookieApp\Protection"))
.SetApplicationName("SharedCookieApp");
//## for BLAZOR COOKIE Auth
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(cfg =>
{
cfg.LoginPath = "/Accout/Login";
cfg.Cookie.Name = ".AspNet.SharedCookie"; //default:.AspNetCore.Cookies
cfg.Cookie.Path = "/";
});
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
//# 註冊:客製服務
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
[...略...]
var app = builder.Build();
[...略...]
app.UseRouting();
//# for BLAZOR COOKIE Auth
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
//## Endpoints
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();