Cookie-based authentication implementation

First, the new project initialization

New AdminController.cs in the Controllers folder

Setting the View

@{
    ViewData["Title"] = "Admin";
}
<h2>@ViewData["Title"]</h2>

<p>Admin Page</p>

Run the show:

Two, Cookie-based accreditation

1, to add AdminController [the Authorize] tab

Tips To quote the space can be.

2, a cookie dependency injection process Startup

Add method under ConfigureServices

services.AddAuthentication (CookieAuthenticationDefaults.AuthenticationScheme)   
.AddCookie (Options => { // custom landing address, if not configured as the default HTTP: // localhost: 5000 / the Account / the Login   
options.LoginPath = " / the Account / mylogin " ;   
});  

Tips To quote the space can be.

 To Configure then approach the cookie middleware also add in, otherwise the certificate authority is not in force

        public  void the Configure (App IApplicationBuilder, IHostingEnvironment the env) 
        { 
            IF (env.IsDevelopment ()) 
            { 
                app.UseDeveloperExceptionPage (); 
            } 
            the else 
            { 
                app.UseExceptionHandler ( " / Home / Error " ); 
            } 

            app.UseStaticFiles (); 
            App. UseCookiePolicy (); 

            // Note app.UseAuthentication method must be placed in front of the following app.UseMvc method, whether the person behind the calls HttpContext.SignInAsync even after the user logs on, use
             // the HttpContext.User will still show the user is not logged in, and HttpContext.User.Claims not read any information logged-on user.
            //This shows that a large impact Asp.Net OWIN frame MiddleWare calling sequence will the system function, the order of each call must not MiddleWare anti 
            app.UseAuthentication (); 

            app.UseMvc (routes => 
            { 
                routes.MapRoute ( 
                    name: " default " , 
                    Template: " {Controller} = Home / Index = {Action} / {ID?} " ); 
            }); 
        }

Here the way app.UseAuthentication is used to doing, app.UseAuthentication enabled Authentication middleware, the middleware will be set HttpContext.User properties based on information currently Cookie Http request (will be used later), so only in after app.UseAuthentication method of registering middleware to be able to read from HttpContext.User in value, which is why app.UseAuthentication highlighted above method must be placed in front of the following app.UseMvc method, because the only way of ASP.NET Core MVC middleware to read the value of HttpContext.User.

Discovery has landed automatically jump to the address.

 3, simulated landing

 Temporarily not landing, just simulate what landing, first create a AccountController.cs

Add two API for login and logout

    public class AccountController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        //登陆
        public IActionResult MakeLogin()
        {
            var claims = new List<Claim>(){
                new Claim(ClaimTypes.Name,"wangyuting"),
                new Claim(ClaimTypes.Role,"admin")
            };
            //必须要加CookieAuthenticationDefaults.AuthenticationScheme,不然无法解析
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
            return Ok();
        }
        //登出
        public IActionResult Logout()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return Ok();
        }

    }

 

 

Cookie authentication using login user in ASP.NET CORE FormsAuthentication conventional methods and are not the same, the steps outlined below:

  • Creating Claim type of array, Claim all types of string key information (such as user name) is stored in the user's login to the
  • The array of Claim type incoming ClaimsIdentity created above, the object is used to construct a ClaimsIdentity
  • The ClaimsIdentity objects created above the incoming ClaimsPrincipal, the objects used to construct a ClaimsPrincipal
  • Call HttpContext.SignInAsync method, passing ClaimsPrincipal objects created above, to complete the user login

So we can see the whole ASP.NET CORE's Cookie authentication login process is much more complex than was previously the ASP.NET FormsAuthentication, after all, before a FormsAuthentication.SetAuthCookie method to get.

 

In the example in this article we default in the project HomeController created a method Acion Login, to implement the code user login. Of course, we realize here is the most simple login Cookie, in fact, the following code can also set whether persistent Cookie, Cookie how long expired, what is the name of Cookie is stored login user information, and we do not introduce too much, Finally, you can read the official documentation for the recommended two more.

Login Method codes are as follows:

///  <Summary> 
/// The Action Wangdacui user to log Core Asp.Net
 ///  </ Summary> 
public IActionResult the Login () 
{ 
    // The following claims are variable Claim array type, a key type string Claim value pairs, claims the array can store any number and information about the user,
     // but should pay attention to after this information is encrypted and stored in the client browser a cookie, so it is best not to store too much information is particularly sensitive, here we only store the user name to the claims array
     // represents the user who is currently logged 
    var claims = new new [] { new new the Claim ( " userName " , " Wangdacui " )}; 

    var claimsIdentity = new new claimsIdentity ( 
    claims,
    CookieAuthenticationDefaults.AuthenticationScheme); 

    ClaimsPrincipal User = new new ClaimsPrincipal (claimsIdentity); 

    Task.Run ( the async () => 
    { 
        // log the user, corresponds to the ASP.NET FormsAuthentication.SetAuthCookie 
        the await HttpContext.SignInAsync (CookieAuthenticationDefaults.AuthenticationScheme, User) ; 

        // may be used to define overloaded method HttpContext.SignInAsync persistent cookie store user authentication information, for example, the following code defines the user logs within 60 minutes after the cookie will remain on the client computer's hard drive,
         // even when the user closes the a browser to access the site again within 60 minutes is still logged in, unless you call the Logout method log off.
         // Note which AllowRefresh property, if AllowRefresh is true, that if a user logs in more than 50% of the time interval ExpiresUtc He has visited the site, on the extension of the user's logon time (in fact, extend the cookie retention time on the client computer's hard disk),
         //For example in this case we have the following property set ExpiresUtc 60 minutes, then when the user logs in more than 30 minutes and less than 60 minutes visited site, the user will be logged and then extended to 60 minutes after the current time. But within 30 minutes after the user logged on to access the site will not extend the login time,
         // because ASP.NET Core there is a mandatory requirement, the user is in a more than 50% of ExpiresUtc time interval by a visit to the site, and not to extend user login time.
        // If AllowRefresh is false, indicating that the user logs within 60 minutes with or without access to the site, only 60 minutes, and flew in a non-logged (not to extend the cookie retention time on the client computer's hard drive, 60 minutes to the client The computer will automatically delete Cookie) 
        / * 
        the await HttpContext.SignInAsync ( 
        CookieAuthenticationDefaults.AuthenticationScheme, 
        User, new new AuthenticationProperties () 
        { 
            isPersistent = to true, 
            ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes (60), 
            AllowRefresh = to true 
        }); 
        * / 

    }). wait (); 

    return View();
}

If the current Http requests have been logged in user A, now call the login method HttpContext.SignInAsync user B, then to the cancellation of the user A, user B login

3. Read the login user information

So how users log in to the user's login information (such as user name) read out of it? We demonstrate how to determine whether the current user has logged in, the user name to log in and read the user's code Index Index method follows the method HomeController shown:

///  <Summary> 
/// The Action determines whether the user has logged in, if already logged in, the login user name read
 ///  </ Summary> 
public IActionResult Index () 
{ 
    // If HttpContext.User.Identity .IsAuthenticated as to true,
     // or HttpContext.User.Claims.Count () is greater than 0 indicates that the user has logged in 
    IF (HttpContext.User.Identity.IsAuthenticated) 
    { 
        // here we can HttpContext.User.Claims by this Action in Login all stored in the cookie
         // Claims value pairs are read out, such as we have just Wangdacui UserName value defined here is read out 
        var the userName = HttpContext.User.Claims.First () the value;. 
    } 

    return View (); 
}

Note that the best use HttpContext.User.Identity.IsAuthenticated to determine whether the user has logged in

Logout

So how do log off the logged-on user? We demonstrate the Logout method HomeController of how a user logs off, the code is as follows:

///  <Summary> 
/// user logs off from the Action in Asp.Net Core
 ///  </ Summary> 
public IActionResult Zimbabwe Logout () 
{ 
    Task.Run ( the async () => 
    { 
        // Log off the user's corresponds in ASP.NET the FormsAuthentication.SignOut   
        the await HttpContext.SignOutAsync (); 
    .}) the Wait (); 

    return View (); 
}

If the current Http request would have no login user, when calling the method is also not being given HttpContext.SignOutAsync

Guess you like

Origin www.cnblogs.com/fger/p/11415636.html