NET8 Blazor App 設定 Windows 驗證
引言
想讓網頁有認證,但不想用 Cookie 也不想用 Bearer token (access token) 認證。其實 IIS 也有支援 Windows 驗證,就來用看看吧。
參考文章
開發環境
平台: NET8 IDE: Visual Studio 2022 框架: Blazor Web App + Server interactive\Per page 語言: C#12
關鍵知識
在 ASP.NET Core 中設定 Windows 驗證在不同部署環境採用的驗證模組就不同,比如 IIS/IIS Express、Kestrel、Kerberos 、Linux 和 macOS 等都有所不同。本例只討論 IIS/IIS Express 在 Windows 環境。
最關健的部份只有一項,加入Negotiate
驗證模組。其他認證相關部份相同寫法一樣。
using Microsoft.AspNetCore.Authentication.Negotiate;
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
關鍵程式碼
安裝套件
PM> Install-Package Microsoft.AspNetCore.Authentication.Negotiate
在 Program.cs 加入Negotiate
驗證模組。
using Microsoft.AspNetCore.Authentication.Negotiate;
using N8BlazorServerWinAuth.Components;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
//# for Auth
//------※ 加入Negotiate驗證模組。其他認證相關部份相同寫法一樣。
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
//# for Auth
builder.Services.AddCascadingAuthenticationState();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// 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.UseAntiforgery();
//# for Auth
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
這樣就完成了。沒錯完成了。接下來取得認證的 HttpContext, AuthorizeView 元件、Task<AuthenticationState> 使用方法與限制都一樣。
部署注意事項
依照文件說明,只需調整 Web.config 設定把windowsAuthentication
開啟,再把anonymousAuthentication
關閉即可。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<!-- <security> 實際上這段設定會與 IIS 本身的組態衝突!
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security> -->
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\N8BlazorServerWinAuth.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
但是實際上這段設定會與 IIS 本身的組態衝突!解法是直接調整 IIS 的設定。如下:
一、先確定已定安裝 IIS 安全性模組【Windows 驗證】。

二、到 IIS 目標網站設定【驗證】

把『Windows 驗證』啟用;把『匿名驗證』停用。

沒圖沒真象

完整原碼
(EOF)
Last updated