net-core
  1. net-core-cookie-and-jwt-authentication

Cookie and JWT Authentication in ASP.NET Core

ASP.NET Core comes with built-in support for both cookie and JWT authentication. In this page, we'll discuss both of these authentication methods, their syntax, examples, output, explanations, uses, important points, and a summary of both.

Cookie Authentication

Cookie authentication works by storing information in an encrypted cookie on the client side. When a user sends a request to the server, the server reads the cookie and authenticates the user based on its contents.

Syntax

To configure cookie authentication in ASP.NET Core, you need to add the following code to the ConfigureServices method in the Startup.cs file:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "YourCookieName";
        options.LoginPath = "/Account/Login";
    });

The AddCookie method adds the cookie authentication middleware to the ASP.NET Core middleware pipeline. You can also specify the cookie name and login path using the CookieAuthenticationOptions class.

Example

To use cookie authentication, you need to first authenticate the user, as shown in the following example:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    var user = await _userManager.FindByNameAsync(model.Email);
    if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id),
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.Email, user.Email)
        };

        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var principal = new ClaimsPrincipal(identity);

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

        return RedirectToAction("Index", "Home");
    }

    ModelState.AddModelError("", "Invalid username or password");
    return View(model);
}

Output

When a user logs in, the server creates an encrypted cookie containing the user's authentication information. This cookie is then sent to the client, where it is stored in the browser's cookies. On subsequent requests, the client sends the cookie back to the server, and the server uses it to authenticate the user.

Explanation

Cookie authentication works by storing a cookie on the client side that contains the user's authentication information. When a user logs in, the server creates this cookie and sends it to the client. On subsequent requests, the client sends the cookie back to the server, and the server uses it to authenticate the user.

Use

Cookie authentication is useful when you need to maintain state between requests and can be a good choice for server-rendered web applications.

Important Points

  • Cookie authentication stores authentication information in a cookie on the client side.
  • Cookie authentication can maintain state between requests and is useful for server-rendered web applications.

JWT Authentication

JWT authentication works by exchanging encrypted tokens between the client and the server. When a user logs in, the server creates a JWT token containing the user's authentication information. This token is then sent to the client, where it is stored on the client side. On subsequent requests, the client sends the JWT token back to the server, and the server uses it to authenticate the user.

Syntax

To configure JWT authentication in ASP.NET Core, you need to add the following code to the ConfigureServices method in the Startup.cs file:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = "YourIssuer",
            ValidAudience = "YourAudience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))
        };
    });

The AddJwtBearer method adds the JWT authentication middleware to the ASP.NET Core middleware pipeline. You can specify the issuer, audience, and secret key using the TokenValidationParameters class.

Example

To use JWT authentication, you need to first authenticate the user and generate a JWT token, as shown in the following example:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    var user = await _userManager.FindByNameAsync(model.Email);
    if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("YourSecretKey");
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email)
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return Ok(new { token = tokenHandler.WriteToken(token) });
    }

    ModelState.AddModelError("", "Invalid username or password");
    return BadRequest();
}

Output

When a user logs in, the server generates a JWT token containing the user's authentication information. This token is then sent to the client, where it is stored on the client side. On subsequent requests, the client sends the JWT token back to the server, and the server uses it to authenticate the user.

Explanation

JWT authentication works by exchanging encrypted tokens between the client and the server. When a user logs in, the server creates a JWT token containing the user's authentication information. This token is then sent to the client, where it is stored on the client side. On subsequent requests, the client sends the JWT token back to the server, and the server uses it to authenticate the user.

Use

JWT authentication is useful when you need to maintain stateless authentication between requests and can be a good choice for client-side web applications.

Important Points

  • JWT authentication exchanges encrypted tokens between the client and the server.
  • JWT authentication can maintain stateless authentication between requests and is useful for client-side web applications.

Summary

In this page, we discussed cookie and JWT authentication in ASP.NET Core. Both methods use encrypted authentication information to authenticate users and are useful for different types of web applications. Cookie authentication is useful for server-rendered web applications that need to maintain state between requests, while JWT authentication is useful for client-side web applications that need to maintain stateless authentication between requests.

Published on: