LoginSignup
1
1

More than 1 year has passed since last update.

ASP.NET Coreの認証と認可でポリシー・ベースかつCookie認証を使用するwithout Identity.

Posted at

この記事の目的

ASP.NET CoreでWebアプリを作成中に認証と認可の仕組みが必要になった。
Cookieで認証情報(ClaimPrincipalと呼ばれるクラス)をクライアントへ渡すAPIを作る公式ドキュメントはある。
ポリシー(要件と認可のハンドラーのセット)・ベースの認可の仕組みを作る公式ドキュメントはある。
しかし、二つを繋ぐドキュメントが見当たらないので、メモしておく。
誰かの役に立てば幸い。

大部分の綺麗なコードは公式ドキュメントを見てほしい。
以下のコードはポイントになりそうな部分を抜粋した。

メモ程度のコード

Program.csで初期化処理時に認可ポリシーを定義して、プログラムに登録する。
「認証スキームにはCookieAuthenticationDefaults.AuthenticationSchemeを使用するということ」を認可ポリシービルダー(AuthorizationPolicyBuilder policy)にAddAuthenticationSchemesで知らせている。
これは推測だが、認可側のエンジンに「ポリシーSomPolicyでは、使用している認証スキームはCookieAuthenticationDefaults.AuthenticationSchemeですよ」ということを知らせることでクレーム(認証時に認証エンジンによってクライアントへのレスポンスに付与される情報)の取り扱い方などを判断させているのだと思う。

認証処理に使用する認証スキームも登録する。

Program.cs
// Authorization
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("SomePolicy", (AuthorizationPolicyBuilder policy) =>
    {
        policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
        policy.AddRequirements(new SomeRequirement());
        // policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
        // policy.Requirements.Add(new SomeRequirement());
        // という書き方もできるようです。
    });
});
builder.Services.AddSingleton<IAuthorizationHandler, SomePolicyHandler>();
// Authentication
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

認可ハンドラーは要件SomeRequirementを使用する(ジェネリックとして指定する)ハンドラーとしてAuthorizationHandlerを継承した上で実装する。
認可の処理は要件SomeRequirementとClaimがメソッドに渡されるので、それらを使って検証処理を行うようにする。
以下はSomePolicyHandlerの定義の部分の抜粋。

SomePolicyHandler.cs クラスの定義部分
public class SomePolicyHandler : AuthorizationHandler<SomeRequirement>

認可が必要なアクションにはAuthoriza属性をつける。
ここでは使用する認可ポリシーを指定する。
以下は認可を必要とするコントローラクラスのアクションメソッド部分を抜粋。

SomeController.cs
    public class SomeController : Controller
    {
        [HttpGet]
        [Authorize(Policy = "SomePolicy")]
        public IActionResult Index()
        {
            return View();
        }
    }

認証処理を実装するアクションで認証スキームとしてCookieAuthenticationDefaults.AuthenticationSchemeを使うことを第一引数で指定している。
Claimなどの扱いは公式ドキュメントを見てほしい。
以下は、認証処理を実施するコントローラクラスの認証アクションメソッド内にて実施が必要な処理の抜粋。

LoginController.cs ログイン処理を実装するコントローラ
    await HttpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,
        new ClaimsPrincipal(claimsIdentity),
        authProperties
    );

参考
https://docs.microsoft.com/ja-jp/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0
https://docs.microsoft.com/ja-jp/aspnet/core/security/authorization/policies?view=aspnetcore-6.0
https://docs.microsoft.com/ja-jp/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-6.0

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