[ASP.NET Core] The simplest example of Cookie Authentication and Authorization

Previous mentioned [ASP.NET MVC] [Owin] with the most simple Cookie authentication,

The change of Microsoft.AspNetCore.Authentication.Cookies ASP.NET Core exercises easiest Cookie authentication and authorization,


  1. Added project.json of dependencies
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"

    And remember each addition to be complete suite reduction (Visual Studio suite automatically revert), then write their own commands to the project directory, use Command Line input dotnet restore manually restore

  2.  In the embodiment Startup Configuration plus class using the CookieAuthentication
               app.UseCookieAuthentication(new CookieAuthenticationOptions()
                {
                    AuthenticationScheme = "MyCookieMiddlewareInstance",
                    LoginPath = new PathString("/Test/Index/"),
                    AutomaticAuthenticate = true,
                    AutomaticChallenge = true
                });

    CookieAuthenticationOption properties refer to the official network description, at the bottom will provide a reference link

  3. The simplest example of login, it is important ClaimsIdentity constructor second argument is authenticationType sure to fill, or verify that no action Http Response Hreaders not have Set-Cookie

            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. Like not want to change or Action which Controller authorized manner, for example,
            [Authorize]
            public IActionResult Index()
            {
                return View();
            }

Reference article

Using Cookie Middleware without ASP.NET Core Identity

Original: Large column  [ASP.NET Core] The simplest example of Cookie Authentication and Authorization


Guess you like

Origin www.cnblogs.com/chinatrump/p/11458443.html