備忘録

備忘録

ASP.NETでBASIC認証を実装する方法

Ⅰ. はじめに

タイトルの通り「ASP.NETBASIC認証する方法」です。

Ⅱ. やり方

1. 必要なパッケージをインストールする
dotnet add package idunno.Authentication.Basic --version 2.3.0
2. プログラムを書く

Startup.cs

using idunno.Authentication.Basic;
using System.Security.Claims;

public void ConfigureServices(IServiceCollection services)
{
  var username = "abc";
  var password = "def";

  services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme).AddBasic(options =>
  {
    // options.Realm = "idunno";
    // https 以外でもBASIC認証を許可する
    // options.AllowInsecureProtocol = true;
    options.Events = new BasicAuthenticationEvents
    {
      OnValidateCredentials = context =>
      {
        if (context.Username == username && context.Password == password)
        {
          var claims = new[]
          {
            new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
          };

          context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
          context.Success();
        }

        return Task.CompletedTask;
      }
    };
  });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  app.UseAuthentication();
  app.UseRouting();

  // 必ず app.UseRouting と app.UseEndpoints の間に入れる
  app.UseAuthorization();

  app.UseEndpoints(endpoints =>
  {
    endpoints.MapControllers();
  });
}

BasicAuthTestController.cs

[ApiController]
[Route("[controller]")]
public class BasicAuthTestController : ControllerBase
{
  [HttpGet("1")]
  public string Get1()
  {
    return "認証なしページ";
  }

  [Authorize]
  [HttpGet("2")]
  public string Get2()
  {
    return "認証ありページ";
  }
}

実行結果