0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】Blazor Server + Microsoft Entra ID ログイン・ログアウト最小実装

0
Posted at

この構成では、ライブラリ Microsoft.Identity.Web.UI が提供する既存のコントローラーを、標準の HTML <a> タグで直接呼び出します。

1. appsettings.json の構成

まずは認証の基盤となる設定です。

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "あなたのドメイン.onmicrosoft.com",
    "TenantId": "あなたのテナントID",
    "ClientId": "あなたのクライアントID",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath": "/signout-callback-oidc"
  }
}

2. Program.cs の構成

MapControllers を呼び出すことで、/MicrosoftIdentity/Account/SignIn などのエンドポイントが有効になります。

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// 認証・UIコントローラーの追加
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddCascadingAuthenticationState();
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseAntiforgery();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

3. ログイン・ログアウトボタンの実装 (aタグ)

複雑なメソッドは使用せず、直接リンクを記述します。

LoginDisplay.razor

<AuthorizeView>
    <Authorized>
        @* ログイン中:名前を表示し、サインアウトエンドポイントへリンク *@
        <span class="me-3">こんにちは、@context.User.Identity?.Name さん</span>
        <a href="MicrosoftIdentity/Account/SignOut" class="nav-link btn btn-link">
            ログアウト
        </a>
    </Authorized>
    <NotAuthorized>
        @* 未ログイン:サインインエンドポイントへリンク *@
        <a href="MicrosoftIdentity/Account/SignIn" class="nav-link btn btn-link">
            ログイン
        </a>
    </NotAuthorized>
</AuthorizeView>

まとめ

Blazor ServerでEntraログイン状態からログアウトする方法をまとめました。

この記事が皆様のコーディングライフの助けになれば幸いです。


参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?