.Net Core certification authority Cookie-based authentication & authorization .Scheme, Policy extension

In the authentication, if need permission to access a Action, the idea is beginning, which Action needs permission to access, we write to the above characteristics can be marked, [TypeFilter (typeof (CustomAuthorizeActionFilterAttribute))]

/// <summary>
 /// 这是一个Action的Filter`  但是用作权限验证
 /// </summary>
 public class CustomAuthorizeActionFilterAttribute : Attribute, IActionFilter
 {
     private ILogger<CustomAuthorizeActionFilterAttribute> _logger = null;
     public CustomAuthorizeActionFilterAttribute(ILogger<CustomAuthorizeActionFilterAttribute> logger)
     {
         this._logger = logger;
     }

     public void OnActionExecuting(ActionExecutingContext context)
     {
         //取出Session
         var strUser = context.HttpContext.Session.GetString("CurrentUser");
         if (!string.IsNullOrWhiteSpace(strUser))
         {
             CurrentUser currentUser = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUser>(strUser);
             _logger.LogDebug($"userName is {currentUser.Name}");
         }
         else
         { 
             context.Result = new RedirectResult("~/Fourth/Login");
         }
          
     }
     public void OnActionExecuted(ActionExecutedContext context)
     {
         //context.HttpContext.Response.WriteAsync("ActionFilter Executed!");
         Console.WriteLine("ActionFilter Executed!");
         //this._logger.LogDebug("ActionFilter Executed!");
     }

 }

Of course, first used in the service inside Session of service == "services.AddSession ();

But this is not good. Under Core .Net framework, there is a characteristic Authorize, when we need to use, in an Action to the top mark

 [Authorize]
 public IActionResult Center()
 {
     return Content("Center");
 }

Let's look at the run, will be reported abnormal

 

 Because we do not use the service in .Net Core below, is not enabled by default authorization filter. This is also a benefit of Core .Net framework, we need only use. Framework do little lighter.

Below we use filters authorized service in which service

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
    AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
o =>
    {
        o.LoginPath = new PathString("/Home/Login");
    });

Just browse the page again, which would request to the login page, the page will just request as a parameter

 

Of course, also use app.UseAuthentication (); This middleware.

In .Net Core inside, save logged in, Cookie is a way through. Use ClaimsIdentity and ClaimsPrincipal

public ActionResult the Login ( String name, String password) 
{ 
    the this ._ilogger.LogDebug ($ " {{name}} login password system " );
     #region there should be a query to the database to verify 
    the CurrentUser the currentUser = new new the CurrentUser () 
    { 
        ID = 123 , 
        the Name = " Bingle " , 
        the Account = " Administrator " , 
        Password = " 123456 "  ,
        In Email= "[email protected]",
        LoginTime = DateTime.Now,
        Role = name.Equals("Bingle") ? "Admin" : "User"
    };
    #endregion

    #region cookie
    {
        ////就很像一个CurrentUser,转成一个claimIdentity
        var claimIdentity = new ClaimsIdentity("Cookie");
        claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, currentUser.Id.ToString()));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Name, currentUser.Name));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Email, currentUser.Email));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Role, currentUser.Role));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Sid, currentUser.Id.ToString()));
        var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
        base.HttpContext.SignInAsync(claimsPrincipal).Wait();//不就是写到cookie
    }
    #endregion

    return View();
}

Log in again, we can see such a Cookie

 

 After that, we go to visit Genter page, or find and return the results of before, or not to visit. Why is this? Because we hit the top label in Action [Authorize], nothing to modify our doing

 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
 public IActionResult Center()
 {
     return Content("Center");
 }

Now we visit again and found that you can visit a success

 

 

 

By User.FindFirstValue (ClaimTypes.Sid); this way, we can get the value of the deposit.

Scheme, Policy extension

Scheme

#region 设置自己的schema的handler 
 services.AddAuthenticationCore(options => options.AddScheme<MyHandler>("myScheme", "demo myScheme"));
 #endregion
 #region  Schame 验证

 services.AddAuthentication(options =>
 {
     options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;// "Richard";//  
 })
 .AddCookie(options =>
 {
     options.LoginPath = new PathString("/Fourth/Login");//If the authentication is not specified here by the jump to the page to 
     options.ClaimsIssuer = " cookies " ; 
 });

Policy

 #region support policy authentication and authorization services   // specified by the policy validation strategy column 
 services.AddSingleton <IAuthorizationHandler, AdvancedRequirement> (); 
 services.AddAuthorization (Options => 
 { // AdvancedRequirement can be understood as an alias 
     options.AddPolicy ( " AdvancedRequirement " , Policy => 
     { 
         policy.AddRequirements ( new new NameAuthorizationRequirement ( " . 1 " )); 
     }); 
 }) AddAuthentication (Options. => 
 { 
     options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;

 

     
 })
 .AddCookie(options =>
 {
     options.LoginPath = new PathString("/Fourth/Login");
     options.ClaimsIssuer = "Cookie";
 });

 #endregion

Also you need to be used in intermediate process Configure

app.UseSession (); 
app.UseCookiePolicy (); //
 app.UseAuthentication (); // identifies the rights to use this certification in the current system

 

Guess you like

Origin www.cnblogs.com/taotaozhuanyong/p/11594931.html