web apiでcookie認証を使用している場合、認証を必要とするapiにはコントローラクラスまたはコントローラクラスのアクションに[Authorize]属性を付与します。システムの種類にも依りますが、ログイン以外のapiは基本的に認証が必要な場合があります。このような場合、個々のコントローラクラスに[Authorize]属性を付けていると、属性の付け漏れが発生します。今回はデフォルトで[Authorize]属性を付与する方法を紹介します。
環境(バージョン)
.NETのバージョン
% dotnet --version 5.0.302
本題
デフォルトで[Authorize]属性を付与するにはStartup.csにフィルターを追加します。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
// デフォルトで[Authorize]属性を付与
var authFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
options.Filters.Add(authFilter);
});
}
これですべてのアクションが認証が必要になります。逆に匿名アクセスを許すアクションには[AllowAnonymous]属性を付与する必要があります。
コントローラのサンプル
ログイン、ログアウトを行うコントローラをサンプルにします。loginアクションは匿名アクセスを許可し、logoutアクションは認証が必要な想定です。
Startup.cs修正前のコントローラ
[ApiController]
[Route("api/[Controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public IActionResult PostLogin(string userId, string password)
{
if ("hoge@co.jp".Equals(userId))
{
var claims = new Claim[]
{
new Claim("ID", userId),
new Claim("Name", "山田 太郎")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// 認証情報をクライアントに返却
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)).Wait();
return Ok();
}
return new UnauthorizedResult();
}
[HttpPost("logout")]
[Authorize]
public IActionResult PostLogout()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).Wait();
return Ok();
}
}
Startup.cs修正後のコントローラ
[ApiController]
[Route("api/[Controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
[AllowAnonymous]
public IActionResult PostLogin(string userId, string password)
{
if ("hoge@co.jp".Equals(userId))
{
var claims = new Claim[]
{
new Claim("ID", userId),
new Claim("Name", "山田 太郎")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// 認証情報をクライアントに返却
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)).Wait();
return Ok();
}
return new UnauthorizedResult();
}
[HttpPost("logout")]
public IActionResult PostLogout()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).Wait();
return Ok();
}
}


コメント