MSDN Documentation

ASP.NET Core Authentication & Authorization

Learn how to implement secure authentication and authorization mechanisms in your ASP.NET Core applications. This tutorial covers common scenarios and best practices.

1. Understanding Authentication Concepts

Authentication is the process of verifying the identity of a user. ASP.NET Core provides a flexible middleware pipeline to handle authentication.

Key concepts include:

  • Authentication Schemes: Mechanisms like cookies, JWT tokens, OAuth, etc.
  • Identity: Represents the authenticated user and their claims.
  • Claims: Pieces of information asserted about a user (e.g., name, role).

Refer to the Authentication API documentation for more details.

2. Implementing Cookie Authentication

Cookie authentication is a common method for web applications. Users log in, and a cookie is set in their browser.

Steps:

  1. Add the necessary NuGet packages: Microsoft.AspNetCore.Authentication.Cookies.
  2. Configure the cookie authentication middleware in Startup.cs (or Program.cs in .NET 6+).
  3. Implement login and logout logic using the SignInAsync and SignOutAsync methods.

Example snippet in Program.cs:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                        .AddCookie(options =>
                        {
                            options.LoginPath = "/Account/Login";
                            options.LogoutPath = "/Account/Logout";
                        });

                    builder.Services.AddAuthorization(); // Required for authorization

                    var app = builder.Build();

                    app.UseHttpsRedirection();
                    app.UseRouting();

                    app.UseAuthentication(); // Must be before UseAuthorization
                    app.UseAuthorization();

                    app.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");

                    app.Run();

3. Implementing JWT Bearer Authentication

JSON Web Tokens (JWT) are often used for APIs, especially in client-server architectures.

Steps:

  1. Add the JWT Bearer authentication package: Microsoft.AspNetCore.Authentication.JwtBearer.
  2. Configure JWT bearer authentication in your service configuration.
  3. Your API endpoints will require the [Authorize] attribute.

Example configuration:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                        .AddJwtBearer(options =>
                        {
                            options.TokenValidationParameters = new TokenValidationParameters
                            {
                                ValidateIssuer = true,
                                ValidateAudience = true,
                                ValidateLifetime = true,
                                ValidateIssuerSigningKey = true,
                                ValidIssuer = Configuration["Jwt:Issuer"],
                                ValidAudience = Configuration["Jwt:Audience"],
                                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                            };
                        });

4. Understanding Authorization

Authorization is the process of determining whether an authenticated user has permission to perform a specific action or access a resource.

ASP.NET Core supports declarative authorization using attributes and programmatic authorization within controller actions.

  • [Authorize]: Requires authentication.
  • [Authorize(Roles = "Admin,User")]: Requires the user to be in the specified roles.
  • [Authorize(Policy = "CanEditArticle")]: Requires a custom authorization policy to be met.

5. Implementing Role-Based Authorization

Assign users to roles and restrict access based on these roles.

Ensure your User.IsInRole() checks are functional, typically populated by your identity provider.

[Authorize(Roles = "Administrator")]
                    public IActionResult AdminPanel()
                    {
                        return View();
                    }

6. Custom Authorization Policies

For more complex authorization logic, define custom policies.

Example policy definition in Startup.cs (or Program.cs):

builder.Services.AddAuthorization(options =>
                    {
                        options.AddPolicy("CanEditArticle", policy =>
                            policy.RequireAuthenticatedUser()
                                  .RequireClaim("CanEdit", "true"));
                    });

Applying the policy:

[Authorize(Policy = "CanEditArticle")]
                    public IActionResult EditArticle(int id)
                    {
                        // ...
                        return View();
                    }

7. Integrating with IdentityServer or OpenID Connect

For advanced scenarios like single sign-on (SSO) or federated identity, ASP.NET Core integrates seamlessly with IdentityServer and other OpenID Connect providers.

This involves configuring the appropriate authentication middleware (e.g., OpenIdConnect) and managing external identity providers.

See the IdentityServer Integration Tutorial.