1
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をEntraで保護

1
Posted at

公式チュートリアルではYARPを使用したブリッジやAPIの保護など複数の要素が混在しているため、シンプルにBlazor ServerをEntraで保護する方法をまとめます。

今回はAspireなし、YARPなしで、対象は Blazor Server のみです。

プロジェクト作成

以下の設定でプロジェクトを作成します。

  • .NET 10
  • 対話型レンダリングモード: Server

Entraにアプリ登録

「アプリの追加」で任意の名前でアプリを登録します。
その後、リダイレクトURIを Webhttps://localhost:7014/signin-oidc として追加します。

ポートはプロジェクトのものに合わせてください。

また、IDトークンの発行設定にもチェックを入れてください。

ライブラリの導入

dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI

appsettings.jsonの設定

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your-tenant.onmicrosoft.com",
    "TenantId": "YOUR_TENANT_ID",
    "ClientId": "YOUR_CLIENT_ID",
    "CallbackPath": "/signin-oidc"
  }
}

Program.csの構成

以下のコードを追加します。

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

var builder = WebApplication.CreateBuilder(args);

// 1. Entra ID 認証サービスの追加
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

// 2. 認可ポリシーとコントローラーの追加 (Sign-out等に必要)
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

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

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();

// 3. 認証・認可ミドルウェアの有効化
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers(); // Sign-out 等のルート用
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

ページの保護

保護したいページに @attribute [Authorize] を追加します。

@page "/counter"
@using Microsoft.AspNetCore.Authorization
@rendermode InteractiveServer
@attribute [Authorize]

<PageTitle>Counter</PageTitle>

動作確認

保護したURLにアクセスして、認証が要求されることを確認します。

まとめ

Blazor ServerにEntraで保護する方法をまとめました。App Serviceにデプロイした場合もリダイレクトURIを設定すれば認証が走ります。

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

参考

1
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
1
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?