Skip to content

Instantly share code, notes, and snippets.

@souri-t
Created March 9, 2023 17:12
Show Gist options
  • Save souri-t/018753fbbb3f4f51716e4289132aa5fd to your computer and use it in GitHub Desktop.
Save souri-t/018753fbbb3f4f51716e4289132aa5fd to your computer and use it in GitHub Desktop.

Blazorアプリ上でWindows認証を実装するためには、以下の手順を実行する必要があります。

  1. ASP.NET Core Identityパッケージをインストールします。
dotnet add package Microsoft.AspNetCore.Identity
  1. Startup.csファイル内に、以下のようにConfigureServicesメソッドを作成します。
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    services.AddHttpContextAccessor();
    services.AddControllersWithViews();
    services.AddRazorPages();
}
  1. 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();
});
  1. 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);
            }
        }
    }
}
  1. ホスト側のWindows認証を構成する必要があります。

Linuxホスト上でBlazorアプリを実行する場合、Kerberos認証を使用してWindows認証を行うことができます。ホスト側で、Kerberos認証を有効にし、HTTPトラフィックを認証する必要があります。

以上の手順に従って、Linux上で動作するBlazorアプリでWindows認証を実装することができます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment