Authentication in .NET Core Web API
🔐 Authentication in .NET Core Web API
Authentication is a key part of securing any .NET Core Web API. It verifies the identity of users before allowing access to protected resources.
ASP.NET Core supports various authentication strategies, such as JWT, Cookie-based, OAuth, and Basic Authentication.
1️⃣ JWT (JSON Web Token) Authentication
JWT is a popular, stateless authentication mechanism often used in APIs. Clients send the token in the request header on every call.
Install JWT Bearer Package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Configure in Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var key = "your_secret_key_here";
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourIssuer",
ValidAudience = "yourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Token Generation Controller
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
public AuthController(IConfiguration config) => _config = config;
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
if (login.Username == "test" && login.Password == "password")
{
var token = GenerateJwtToken(login.Username);
return Ok(new { token });
}
return Unauthorized();
}
private string GenerateJwtToken(string username)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[] { new Claim(ClaimTypes.Name, username) };
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
Secure an Endpoint
[ApiController]
[Route("api/secure")]
[Authorize]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new { message = "This is a secure endpoint." });
}
2️⃣ Cookie-Based Authentication
Best for traditional web apps that maintain user sessions on the server.
Install Cookie Auth Package
dotnet add package Microsoft.AspNetCore.Authentication.Cookies
Configure Authentication
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/api/auth/login";
options.LogoutPath = "/api/auth/logout";
});
Login Endpoint
[HttpPost("login")]
public async Task Login([FromBody] LoginModel login)
{
var claims = new List<Claim> { new Claim(ClaimTypes.Name, login.Username) };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var props = new AuthenticationProperties { IsPersistent = true };
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), props);
return Ok();
}
3️⃣ OAuth Authentication (Google, Facebook, etc.)
Allows users to log in using third-party providers like Google or Facebook.
Install Google Auth Package
dotnet add package Microsoft.AspNetCore.Authentication.Google
Configure OAuth
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
});
⚠️ Basic Authentication (Not Recommended)
Only use Basic Auth for internal tools, prototyping, or over secure channels (with SSL/TLS enforced).
✅ Conclusion
- JWT: Best for stateless APIs and mobile apps.
- Cookie Auth: Ideal for web applications needing sessions.
- OAuth: Use for social logins (Google, Facebook, Microsoft).
- Basic Auth: Avoid unless absolutely necessary and secured with HTTPS.
Choose the method that fits your application’s architecture and security requirements. ASP.NET Core provides flexible and powerful tools for handling authentication securely.
Comments
Post a Comment