.NETのコア認証局クッキーベースの認証&承認.Scheme、ポリシー拡張

認証には、アクションにアクセスする必要が許可すれば、アイデアはアクションがアクセス許可を必要とする、始めて、我々は上記の特性に書き込みをマークすることができ、[のtypeFilter(typeof演算(CustomAuthorizeActionFilterAttribute))]

///  <要約> 
 /// 这是一个行動的Filter`但是用作权限验证
  ///  </要約> 
 パブリック クラスCustomAuthorizeActionFilterAttribute:属性、IActionFilter 
 { 
     プライベート ILoggerです<CustomAuthorizeActionFilterAttribute> _logger = nullを公共 CustomAuthorizeActionFilterAttribute(ILoggerです<CustomAuthorizeActionFilterAttribute> ロガー)
     { 
         この ._logger = ロガー。
     } 

     公共 ボイドOnActionExecuting(ActionExecutingContextコンテキスト)
     { 
         // 取出セッション
         VARstrUser = context.HttpContext.Session.GetString(" あるCurrentUser " )。
         もし(!文字列.IsNullOrWhiteSpace(strUser))
         { 
             あるCurrentUserあるCurrentUser = Newtonsoft.Json.JsonConvert.DeserializeObject <あるCurrentUser> (strUser)。
             _logger.LogDebug($ " usernameは{currentUser.Name}です" )。
         } 
         
         { 
             context.Result =  RedirectResult(" 〜/第四/ログイン" ); 
         } 
          
     } 
     パブリック 無効OnActionExecuted(ActionExecutedContextコンテキスト)
     { 
         // context.HttpContext.Response.WriteAsync( "実行されるのActionFilter!"); 
         Console.WriteLineを(" のActionFilter実行!" );
         // this._logger.LogDebug( "実行されるのActionFilter!"); 
     } 

 }

もちろん、第一サービスのセッション==「services.AddSession()内のサービスに使用されます。

しかし、これは良いではありません。我々はトップマークにアクションで、使用する必要がある場合、コアの.NET Frameworkの下では、特徴的な承認があります

【承認】
  公衆IActionResultセンター()
 { 
     戻りコンテンツ(センター)。
 }

のは、実行を見てみましょう、異常が報告されます

 

 私たちは以下のネットコアでサービスを使用していないので、デフォルトの認証フィルタでは有効になっていません。これは、我々は唯一の使用を必要とし、また、コア.NET Frameworkの利点です。フレームワークは少し軽いん。

私たちは、フィルタを使用するには、以下のサービスでサービスを認可

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)。
    AddCookie(CookieAuthenticationDefaults.AuthenticationScheme、
O => 
    { 
        o.LoginPath = 新しい PathString(" /ホーム/ログイン" ); 
    });

ただ、ログインページに要求するページを再度、閲覧、ページをパラメータとして要求するだけだろう

 

このミドルウェア;もちろん、app.UseAuthentication()を使用します。

内部ネットコアでは、ログインしたセーブ、クッキーは通じ方法です。ClaimsIdentityとClaimsPrincipalを使用します

公共のActionResultログイン(文字列名、文字列のパスワード)
{ 
    この ._ilogger.LogDebug($ {{名前}}ログインパスワードシステムは);
     #regionが確認するために、データベースへのクエリがあるはず
    CurrentUserにあるCurrentUser = 新しい新しいあるCurrentUserを()
    { 
        ID = 123 
        名前 = " Bingle " 
        アカウント = " 管理者" 
        パスワード = " 123456 " 
        メール = " [email protected] " 
        LoginTime = DateTime.Now、
        役割 = name.Equals(" Bingle ")?" 管理者"" ユーザー" 
    }; 
    #endregionの

    #regionのクッキー
    { 
        /// /就很像一个あるCurrentUser、转成一个claimIdentity 
        VAR claimIdentity = 新しい ClaimsIdentity(" クッキー" )。
        claimIdentity.AddClaim(前記(ClaimTypes.NameIdentifier、currentUser.Id.ToString()))。
        claimIdentity.AddClaim(新しい項(ClaimTypes.Name、currentUser.Name))。
        claimIdentity.AddClaim(新しい項(ClaimTypes.Email、currentUser.Email))。
        claimIdentity.AddClaim(新しい項(ClaimTypes.Role、currentUser.Role))。
        claimIdentity.AddClaim(新しい項(ClaimTypes.Sid​​、currentUser.Id.ToString()))。
        VAR claimsPrincipal = 新しいClaimsPrincipal(claimIdentity)。
        ベース .HttpContext.SignInAsync(claimsPrincipal).WAIT(); // 不就是写到クッキー
    }
     #endregionの

    リターン見る(); 
}

私たちは、このようなクッキーを参照することができ、再度ログインします

 

 その後、我々は訪問しGenterページを訪問、または前の結果を見つけて返し、そうでないかに行きます。これはなぜでしょうか?私たちはやって変更することは何も、[承認]アクションでトップラベルを打っていないので

[承認(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
  パブリックIActionResultセンター()
 { 
     戻りコンテンツ(" センター" )。
 }

今、私たちは再び訪問し、あなたが成功を訪問することができますことを発見しました

 

 

 

User.FindFirstValue(ClaimTypes.Sid​​)によって、このように、我々は、預金の値を取得することができます。

スキーム、ポリシー拡張

スキーム

#region设置自己的スキーマ的ハンドラ
 services.AddAuthenticationCore(オプション => options.AddScheme <MyHandlerという>(" myScheme "" デモmyScheme " ));
 #endregion 
 #region   Schame验证

 services.AddAuthentication(オプション => 
 { 
     options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // "リチャード"; //   
})
 .AddCookie(オプション => 
 { 
     options.LoginPath = 新しい PathString(" /四/ログイン");認証のページにジャンプすることにより、ここで指定されていない場合 
     options.ClaimsIssuer = クッキー; 
 });

ポリシー

 #regionのサポートポリシーの認証および認可サービス   // ポリシー検証戦略カラムで指定 
 services.AddSingleton <IAuthorizationHandler、AdvancedRequirement> (); 
 services.AddAuthorizationは、(オプション => 
 { // AdvancedRequirementは、エイリアスとして理解することができる 
     options.AddPolicy(" AdvancedRequirement "ポリシー=> 
     { 
         policy.AddRequirements(新しい新しい NameAuthorizationRequirement(" 1 " )); 
     }); 
 })AddAuthentication(オプション => 
 { 
     options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme。

 

     
 })
 .AddCookie(オプション => 
 { 
     options.LoginPath = 新しい PathString(" /第四/ログイン" ); 
     options.ClaimsIssuer = " クッキー" ; 
 }); 

 #endregion

また、あなたは、中間プロセスの設定で使用する必要があります

app.UseSession(); 
app.UseCookiePolicy(); //
 app.UseAuthenticationは(); //は、現在のシステムでは、この証明書を使用する権利を特定します

 

おすすめ

転載: www.cnblogs.com/taotaozhuanyong/p/11594931.html
おすすめ