Cookie Authentication In Asp.Net Core
Tags: webdev, programming, productivity, opensource
Published: 2023-05-31 16:55:02

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:

```csharp
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
    });
    
    // ...
}
```

3. Configure Middleware: In the `Configure` method of your `Startup.cs` file, add the authentication middleware to the pipeline:

```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    // ...
}
```

4. Protect Controllers/Endpoints: You can protect specific controllers or endpoints by applying the `[Authorize]` attribute to them. For example:

```csharp
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MyController : ControllerBase
{
    // Controller actions...
}
```

5. 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:

```csharp
[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();
}
```

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

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

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.