Blazorアプリ上でWindows認証を実装するためには、以下の手順を実行する必要があります。
- ASP.NET Core Identityパッケージをインストールします。
dotnet add package Microsoft.AspNetCore.Identity
- Startup.csファイル内に、以下のようにConfigureServicesメソッドを作成します。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddHttpContextAccessor();
services.AddControllersWithViews();
services.AddRazorPages();
}
- WebアプリケーションのConfigure メソッドで、認証と必要なリクエスト処理の構成を設定します。
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
- Blazorのコンポーネント内で、以下のようなコードを記述して、認証状態をチェックします。
@page "/"
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<p>You are signed in as @UserManager.GetUserAsync(User).Result.Email</p>
}
else
{
<p>You are not signed in.</p>
}
@code {
protected override async Task OnInitializedAsync()
{
var user = await UserManager.GetUserAsync(User);
if (user != null)
{
var result = await SignInManager.CheckPasswordSignInAsync(user, "password", false);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, false);
}
}
}
}
- ホスト側のWindows認証を構成する必要があります。
Linuxホスト上でBlazorアプリを実行する場合、Kerberos認証を使用してWindows認証を行うことができます。ホスト側で、Kerberos認証を有効にし、HTTPトラフィックを認証する必要があります。
以上の手順に従って、Linux上で動作するBlazorアプリでWindows認証を実装することができます。