Pulse7
7/31/2017 - 11:27 AM

Cookie Authentication

Cookie Authentication

[Route("")]
    public class HomeController:Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [Route("forbidden")]
        public IActionResult Forbidden()
        {
            return View();
        }

        [HttpGet("private")]
        [Authorize]
        public IActionResult Private()
        {
            return View();
        }
    }
[Route("account")]
    public class AccountController:Controller
    {
        [HttpGet("signin")]
        public async Task<IActionResult> SignIn()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,"My Name",ClaimValueTypes.String)
            };
            ClaimsIdentity identity = new ClaimsIdentity(claims,"Custom");
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            await HttpContext.Authentication.SignInAsync("OurAuthenticationCookie", principal);
            var returnUrl = Request.Query["ReturnUrl"];
            return Redirect($"../../{returnUrl}");
        }
    }
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />

var cookieOptions = new CookieAuthenticationOptions()
            {
                AuthenticationScheme="OurAuthenticationCookie",
                LoginPath="/account/signin",
                AccessDeniedPath="/forbidden", //page to show when authorize fails
                AutomaticAuthenticate=true,
                AutomaticChallenge=true,
                CookieHttpOnly=true
            };


            app.UseCookieAuthentication(cookieOptions);