DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Cookie Authentication In Asp.Net Core

In ASP.NET Core Web API, cookie authentication is a common approach used to authenticate and authorize users. It involves issuing and validating authentication cookies, which contain user information and are sent with each request to the API.

Here's an overview of the steps involved in implementing cookie authentication in an ASP.NET Core Web API:

  1. Install Required Packages: Make sure you have the necessary packages installed. The key packages are Microsoft.AspNetCore.Authentication.Cookies and Microsoft.AspNetCore.Authentication.

  2. Configure Authentication: In the ConfigureServices method of your Startup.cs file, add the cookie authentication middleware and configure it:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login"; // Specify the login page URL
        options.AccessDeniedPath = "/Account/AccessDenied"; // Specify the access denied page URL
    });

    // ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Configure Middleware: In the Configure method of your Startup.cs file, add the authentication middleware to the pipeline:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseAuthentication();
    app.UseAuthorization();

    // ...
}
Enter fullscreen mode Exit fullscreen mode
  1. Protect Controllers/Endpoints: You can protect specific controllers or endpoints by applying the [Authorize] attribute to them. For example:
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MyController : ControllerBase
{
    // Controller actions...
}
Enter fullscreen mode Exit fullscreen mode
  1. Login and Logout: Implement login and logout actions in your controller or wherever you handle authentication logic. Typically, the login action would validate the user's credentials, create the authentication cookie, and sign the user in:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginModel model)
{
    // Validate user credentials

    if (validCredentials)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, model.Username)
            // Add additional claims as needed
        };

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

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

        return Ok();
    }

    return Unauthorized();
}
Enter fullscreen mode Exit fullscreen mode

To logout, you can implement a similar action that calls HttpContext.SignOutAsync():

[HttpPost]
[Authorize]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    return Ok();
}
Enter fullscreen mode Exit fullscreen mode

This is a basic overview of how to implement cookie authentication in an ASP.NET Core. Remember to configure the authentication middleware and protect your controllers or endpoints based on your specific requirements.

Top comments (0)