[ASP.NETコア] Cookie認証及び認可の最も簡単な例

最も簡単なクッキー認証で前に述べた[ASP.NET MVC] [Owin]、

Microsoft.AspNetCore.Authentication.Cookies ASP.NETコアの変化は、最も簡単なクッキーの認証および認可を行使する


  1. 依存関係を追加しましproject.json
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"

    そして、復元手動で復元するコマンドライン入力DOTNETを使用して、プロジェクトディレクトリに、独自のコマンドを記述し、完全なスイートの減少(Visual Studioスイートを自動的に戻す)する各添加を覚えています

  2.  実施形態ではスタートアップコンフィギュレーションに加えてクラスがCookieAuthenticationを使用して
               app.UseCookieAuthentication(new CookieAuthenticationOptions()
                {
                    AuthenticationScheme = "MyCookieMiddlewareInstance",
                    LoginPath = new PathString("/Test/Index/"),
                    AutomaticAuthenticate = true,
                    AutomaticChallenge = true
                });

    CookieAuthenticationOption特性は、参照リンクを提供する底部に、公式のネットワークの説明を参照してください

  3. ログインの最も単純な例では、それが重要なClaimsIdentityコンストラクタで二番目の引数は必ず記入してauthenticationTypeある、または何もアクションHTTP応答Hreadersは、クッキーを設定していないではないことを確認してください

            public async Task
        
        
         
          Login()
            {
                var claims = new List
         
         
          
          () {
                    new Claim(ClaimTypes.Name, "Herry"),
                    new Claim(ClaimTypes.Role, "Users")
                };
                var claimsIdentity = new ClaimsIdentity(claims, "myTest");
                var principal = new ClaimsPrincipal(claimsIdentity);
                await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);
    
                return Ok();
            }
         
         
        
        

  4. 以下のようなコントローラは、例えば、方法を認可アクションを変更したりしたくありません、
            [Authorize]
            public IActionResult Index()
            {
                return View();
            }

参考記事

ASP.NETコアアイデンティティなしクッキーミドルウェアを使用して

オリジナル:大カラム  [ASP.NETコア] Cookie認証及び認可の最も簡単な例


おすすめ

転載: www.cnblogs.com/chinatrump/p/11458443.html