IdentityServer4 の機能とアーキテクチャ
IdentityServer4 は ASP.NET Core 向けのオープンソース認証・認可フレームワークで、OpenID Connect と OAuth 2.0 プロトコルをサポートします。主な機能は以下の通りです:
- 統合認証サービス:Web/Mobile/API クライアント向けの集中管理型認証
- シングルサインオン(SSO):複数アプリケーション間の統一ログイン
- API セキュリティ:アクセストークンによるリソース保護
- 外部ID連携:Google/QQ/Azure AD などの外部プロバイダー連携
- 拡張性:カスタムユーザーストレージやトークンロジックの実装が可能
環境構築と設定手順
1. プロジェクト準備
dotnet add package IdentityServer4
dotnet add package IdentityServer4.EntityFramework
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
2. 設定クラスの実装
public static class IdentityServerConfig {
public static IEnumerable<ApiResource> ApiDefinitions => new List<ApiResource> {
new ApiResource("api1", "サンプルAPI")
};
public static IEnumerable<Client> ClientSettings => new List<Client> {
new Client {
ClientId = "web_app",
ClientSecrets = { new Secret("secret_key".Sha256()) },
AllowedGrantTypes = GrantTypes.Code,
RedirectUris = { "https://localhost:5002/signin-oidc" },
AllowedScopes = { "openid", "profile", "api1" }
}
};
}
3. Startup.cs の設定
public void ConfigureServices(IServiceCollection services) {
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(IdentityServerConfig.ApiDefinitions)
.AddInMemoryClients(IdentityServerConfig.ClientSettings)
.AddAspNetIdentity<ApplicationUser>();
}
実際の利用シナリオ
ECサイトでの例
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class OrderController : ControllerBase {
[HttpGet]
public ActionResult<string> GetOrders() {
var userId = User.FindFirst("sub")?.Value;
return Ok($"ユーザー {userId} の注文履歴");
}
}
拡張機能と連携
QQログインの実装
services.AddAuthentication()
.AddOpenIdConnect("QQ", "QQアカウントでログイン", options => {
options.Authority = "https://graph.qq.com/oauth2.0";
options.ClientId = "your_client_id";
options.ClientSecret = "your_secret";
});
ベストプラクティス
- HTTPSの強制:
services.AddHttpsRedirection(options => options.HttpsPort = 443); - 本番用証明書:
AddSigningCredentialで証明書を設定 - PKCEの活用:OAuth 2.0 のコード交換をセキュアに実装
トラブルシューティング
- Swagger 404エラー:XMLドキュメントのパスを確認
- invalid_client エラー:クライアントシークレットのハッシュ値を検証
- CORS問題:
services.AddCors()でポリシーを設定