スポンサーリンク

.NET Web APIでAPIキー認証を実装する方法

APIキーによる認証は、シンプルで導入しやすいため、外部サービスとの連携や簡易的なアクセス制御に広く使われています。この記事では、ASP.NET Core (.NET 8) を使って、APIキー認証を実装する手順を紹介します。

1. カスタム認証ハンドラーの作成

AuthenticationHandler を継承して、APIキー認証のロジックを定義します。

ApiKeyAuthenticationHandler.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Encodings.Web;

public class ApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string ApiKeyHeaderName = "X-API-KEY";
    private readonly string _configuredApiKey;

    public ApiKeyAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock,
        IConfiguration configuration) : base(options, logger, encoder, clock)
    {
        _configuredApiKey = configuration["ApiKey"] ?? throw new ArgumentNullException("ApiKey is not configured.");
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue(ApiKeyHeaderName, out var apiKeyHeaderValues))
        {
            return Task.FromResult(AuthenticateResult.Fail("API Key is missing."));
        }

        var providedApiKey = apiKeyHeaderValues.FirstOrDefault();

        if (_configuredApiKey != providedApiKey)
        {
            return Task.FromResult(AuthenticateResult.Fail("Invalid API Key."));
        }

        var claims = new[] { new Claim(ClaimTypes.Name, "ApiKeyUser") };
        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

2. 認証サービスの登録

Program.cs に認証スキームとハンドラーを登録します。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("ApiKeyScheme")
    .AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>("ApiKeyScheme", null);

builder.Services.AddAuthorization();
builder.Services.AddControllers();

var app = builder.Build();

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

app.MapControllers();

app.Run();

3. 設定ファイルにAPIキーを追加

appsettings.json にAPIキーを設定します。

{
  "ApiKey": "your-secure-api-key"
}

4. 認証が必要なエンドポイントを作成

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
    [HttpGet]
    [Authorize(AuthenticationSchemes = "ApiKeyScheme")]
    public IActionResult GetSecret()
    {
        return Ok("認証されたユーザーのみがこのデータを取得できます。");
    }
}

5. テスト

curl などで以下のようにリクエストを送って確認します。

curl -v -H "X-API-KEY: your-secure-api-key" https://localhost:5001/api/secure

正しいAPIキーが送られていれば、認証が通りデータが取得できます。

 -- 省略 --
> X-API-KEY: your-secure-api-key
>
< HTTP/1.1 200 OK
 -- 省略 --

異なるAPIキーや、APIキーが設定されていなければ、401エラーになります。

-- 省略 --
< HTTP/1.1 401 Unauthorized

まとめ

APIキー認証は、トークンベースの認証と比べてシンプルで、外部システムとの連携時や社内向けAPIに適しています。ただし、キーの管理や漏洩リスクには注意し、必要に応じてレート制限やIP制限と組み合わせると安全性が高まります。

.NET
スポンサーリンク
シェアする
trelab