C# provides various authentication methods for securing applications, whether they're web applications, APIs, or enterprise solutions. Below, we'll cover the most common authentication techniques, including JWT, OAuth2, API Keys, Windows Authentication, and Azure AD with code examples.
1. Password-Based Authentication (With Hashing)
Overview
A common method where users authenticate with a username and password, stored securely using hashing.
Implementation (C# with BCrypt.NET)
-
Install BCrypt.NET via NuGet:
dotnet add package BCrypt.Net-Next
-
Hash and verify passwords
using BCrypt.Net; public class AuthService { public string HashPassword(string password) { return BCrypt.HashPassword(password); } public bool VerifyPassword(string password, string hashedPassword) { return BCrypt.Verify(password, hashedPassword); } }
Pros: Secure (when combined with hashing).
Cons: Still vulnerable to credential stuffing attacks.
2. Token-Based Authentication (JWT)
Overview
JSON Web Token (JWT) is widely used in APIs for stateless authentication.
Implementation (ASP.NET Core API + JWT)
-
Install required package:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
-
Configure authentication in
Program.cs
:using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); var key = Encoding.UTF8.GetBytes("your_secret_key_here"); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization();
-
Generate and validate JWT tokens:
using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using System.Text; public class JwtService { private const string Secret = "your_secret_key_here"; public string GenerateToken(string username) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }), Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } }
Pros: Stateless, widely used in APIs.
Cons: If the token is stolen, it can be used until expiry.
3. OAuth 2.0 and OpenID Connect (Google, Microsoft, Facebook, etc.)
Overview
OAuth2 allows authentication using external providers like Google, Facebook, and Microsoft.
Implementation (OAuth2 with Microsoft Identity & ASP.NET Core)
-
Install required package:
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
-
Configure Microsoft OAuth in
Program.cs
:using Microsoft.AspNetCore.Authentication.OpenIdConnect; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddOpenIdConnect("Microsoft", options => { options.ClientId = "YOUR_MICROSOFT_CLIENT_ID"; options.ClientSecret = "YOUR_MICROSOFT_CLIENT_SECRET"; options.Authority = "https://login.microsoftonline.com/common"; options.CallbackPath = "/signin-oidc"; }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization();
Pros: Secure, no need to store passwords.
Cons: Requires third-party integration.
4. API Key Authentication
Overview
API Keys are commonly used for service-to-service authentication.
Implementation (ASP.NET Core Middleware)
-
Create a middleware to check API keys:
public class ApiKeyMiddleware { private readonly RequestDelegate _next; private const string API_KEY_HEADER = "X-API-KEY"; private const string API_KEY_VALUE = "your_api_key_here"; public ApiKeyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { if (!context.Request.Headers.TryGetValue(API_KEY_HEADER, out var extractedApiKey) || extractedApiKey != API_KEY_VALUE) { context.Response.StatusCode = 401; await context.Response.WriteAsync("Unauthorized: Invalid API Key"); return; } await _next(context); } }
-
Register the middleware in
Program.cs
:var app = builder.Build(); app.UseMiddleware<ApiKeyMiddleware>();
Pros: Simple, efficient for internal services.
Cons: API keys can be leaked if not secured properly.
5. Windows Authentication (Kerberos & NTLM)
Overview
Best for enterprise environments using Active Directory.
Implementation (ASP.NET Core Windows Authentication)
-
Modify
appsettings.json
:{ "iisSettings": { "windowsAuthentication": true, "anonymousAuthentication": false } }
-
Enable Windows Authentication in
Program.cs
:using Microsoft.AspNetCore.Server.IISIntegration; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization();
Pros: Seamless authentication in Windows environments.
Cons: Limited to Windows-based systems.
6. Azure Active Directory (Azure AD) Authentication
Overview
Azure AD provides enterprise-grade authentication, Single Sign-On (SSO), MFA, and role-based access control (RBAC).
Implementation (ASP.NET Core + Azure AD)
-
Install Microsoft Authentication package:
dotnet add package Microsoft.AspNetCore.Authentication.AzureAD.UI
-
Configure authentication in
Program.cs
:using Microsoft.AspNetCore.Authentication.AzureAD.UI; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => builder.Configuration.Bind("AzureAd", options)); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization();
-
Add Azure AD Configuration in
appsettings.json
:{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "yourdomain.com", "TenantId": "your_tenant_id", "ClientId": "your_client_id", "CallbackPath": "/signin-oidc" } }
Pros: Enterprise-grade security, integrates well with Microsoft services.
Cons: Requires Azure AD setup.
Choosing the right authentication method depends on the application type:
Authentication Method | Best For | Security Level | Complexity |
---|---|---|---|
Password Hashing | Small apps | Medium | Low |
JWT | REST APIs | High | Medium |
OAuth2 / OpenID | Third-party login | High | High |
API Key | Service-to-service | Medium | Low |
Windows Auth | Enterprise Windows apps | High | Medium |
Azure AD | Enterprise cloud apps | Very High | High |
For Microsoft enterprise apps, Windows Authentication & Azure AD are ideal. For APIs, JWT is a great choice, while OAuth2 works best for third-party authentication.