Click here to Skip to main content
15,942,706 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core 2.0 Cookie Authentication

Rate me:
Please Sign up or sign in to vote.
4.71/5 (5 votes)
8 Sep 2017CPOL3 min read 36.3K   10   4
How to implement cookie authentication in ASP.NET Core 2.0 Continue reading...

Problem

How to implement cookie authentication in ASP.NET Core 2.0.

Solution

Create an empty project and update Startup to configure services and middleware for MVC and Authentication:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddAuthentication("FiverSecurityScheme")
                    .AddCookie("FiverSecurityScheme", options =>
                    {
                        options.AccessDeniedPath = new PathString("/Security/Access");
                        options.LoginPath = new PathString("/Security/Login");
                    });

            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();
        }

Create a model to receive login details:

C#
public class LoginInputModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

Create a login page:

ASP.NET
<form asp-controller="Security" asp-action="Login" method="post">
    <input type="text" name="username" id="username" />
    <input type="password" name="password" id="password" />
    <input type="submit" value="Login" />
</form>

Create a controller for Login and Logout actions:

C#
public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginInputModel inputModel)
        {
            if (!IsAuthentic(inputModel.Username, inputModel.Password))
                return View();

            // create claims
            List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "Sean Connery"),
                new Claim(ClaimTypes.Email, inputModel.Username)
            };

            // create identity
            ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie");

            // create principal
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            // sign-in
            await HttpContext.SignInAsync(
                    scheme: "FiverSecurityCookie",
                    principal: principal);
            
            return RedirectToAction("Index", "Home");
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(
                    scheme: "FiverSecurityCookie");

            return RedirectToAction("Login");
        }

Finally, add a controller to secure using [Authorize] attribute:

C#
[Authorize]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

Discussion

Authentication middleware intercepts incoming requests and checks for the existence of a cookie holding encrypted user data.

  • If a cookie is found, it will be serialized into a ClaimsPincipal type and can be accessed via HttpContext.User property.
  • If a cookie isn’t found, middleware redirects to login page using an action method. Through the login page, you’ll receive user details and authenticate against your database records. Once authenticated, you’ll need to:
    • Create List<Claim> related to the user identity.
    • Create ClaimsIdentity, assign claims and specify authentication type.
    • Create ClaimsPrincipal and assign identity.
    • Call HttpContext.SignInAsync() with authentication scheme name (setup via services, see next section) and Principal.

Cookie Authentication Options

When setting up cookie services, there are several options to tweak its behaviour like:

  • AccessDeniedPath: Redirects to this path when authorization fails
  • AuthenticationScheme: Name that identifies the scheme, used with signing in and out. In the solution, it’s FiverSecurityScheme
  • Cookie.Domain: Domain used for cookie storage, defaults to request’s host. Browser will only send cookie to matching host
  • Cookie.HttpOnly: Sets whether cookie can be accessed from client side scripts. Default is true, i.e., only accessed via HTTP and not via scripts
  • Cookie.Name: Set to override default name of cookie, which is .AspNetCore.Cookies
  • Cookie.Path: Path where cookie is created, default is ‘/’, i.e., root
  • Cookie.SecurePolicy: Determines if cookie can be accessed via HTTPS requests only
  • ExpireTimeSpan: Determines how long the cookie is valid for
  • LoginPath: Redirects to this page for unauthenticated users
  • ReturnUrlParameter: Name of query string parameter appended to URL when redirected to login path
  • SlidingExpiration: Set to keep the cookie alive once close to expiry time (half way)

Events

Cookie Authentication allows developers to hook into events at various lifecycle stages of authentication process. For instance, you could log successful sign-ins using OnSignedIn or use OnValidatePrincipal (runs on every request) to invalidate the user (e.g. if you want to force sign-out).

Note: For some of the events (e.g. OnValidatePrincipal), the HttpContext.User is null, use the Principal property of event’s context parameter.

C#
Events = new CookieAuthenticationEvents
                {
                    OnSignedIn = context =>
                    {
                        Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
                          "OnSignedIn", context.Principal.Identity.Name);
                        return Task.CompletedTask;
                    },
                    OnValidatePrincipal = context =>
                    {
                        Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
                          "OnValidatePrincipal", context.Principal.Identity.Name);
                        return Task.CompletedTask;
                    },
                },

Sign Out

To delete the authentication cookie, and thus sign out the user, you call HttpContext.SignOutAsync() method with the authentication scheme name.

Cookie Expiration

In order to set an absolute expiry time for the identity/cookie (as opposed to sliding expiration), you could use AuthenticationProperties:

C#
await HttpContext.SignInAsync(
                    scheme: "FiverSecurityScheme",
                    principal: principal,
                    properties: new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(1)
                    });

Migrating from ASP.NET Core 1.x

Prior to ASP.NET Core 2.0, the cookie authentication was setup little differently. It was setup in Configure() method and some of the property names were different too. Below is from the project I originally created using ASP.NET Core 1.x:

C#
app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AccessDeniedPath = new PathString("/Security/Access"),
                AuthenticationScheme = "FiverSecurityCookie",
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieHttpOnly = true,
                CookieName = ".Fiver.Security.Cookie",
                CookiePath = "/",
                CookieSecure = CookieSecurePolicy.SameAsRequest,
                Events = new CookieAuthenticationEvents
                {
                    OnSignedIn = context =>
                    {
                        Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
                          "OnSignedIn", context.Principal.Identity.Name);
                        return Task.CompletedTask;
                    },
                    OnSigningOut = context =>
                    {
                        Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
                          "OnSigningOut", context.HttpContext.User.Identity.Name);
                        return Task.CompletedTask;
                    },
                    OnValidatePrincipal = context =>
                    {
                        Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
                          "OnValidatePrincipal", context.Principal.Identity.Name);
                        return Task.CompletedTask;
                    },
                },
                ExpireTimeSpan = TimeSpan.FromMinutes(5),
                LoginPath = new PathString("/Security/Login"),
                ReturnUrlParameter = "RequestPath",
                SlidingExpiration = true,
            });

Also the sign-in and sign-out methods were accessed using Authentication property on HttpContext:

C#
await HttpContext.Authentication.SignInAsync(
                    authenticationScheme: "FiverSecurityCookie",
                    principal: principal);

            await HttpContext.Authentication.SignOutAsync(
                    authenticationScheme: "FiverSecurityCookie");

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionSignInManager.PasswordSignInAsync() vs HttpContext.SignInAsync() Pin
Pham Dinh Truong23-May-19 7:00
professionalPham Dinh Truong23-May-19 7:00 
QuestionReturn Null --> (ClaimsPrincipal)Thread.CurrentPrincipal; Pin
Pramod Singh (C)9-Apr-18 3:17
professionalPramod Singh (C)9-Apr-18 3:17 
Questionvar identity = (ClaimsPrincipal)Thread.CurrentPrincipal; Retrieve Null Value in between postback page Pin
Pramod Singh (C)9-Apr-18 3:12
professionalPramod Singh (C)9-Apr-18 3:12 
I have implimented and run the application but some time work (
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
) and time same code (
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
) return null in identity. Please suggest.
PraiseThanks for the detailed and complete tutorial! Pin
Sipke Schoorstra15-Jan-18 6:12
Sipke Schoorstra15-Jan-18 6:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.