Don’t roll your own auth. In 2021, securing an API means efficiently implementing OAuth2/OIDC validation for JWT tokens.
The Theory
Your API should not handle login. A separate Identity Provider (IdP) – like Azure AD, Auth0, or IdentityServer – issues a standard JWT Access Token. Your API’s only job is to validate the signature and claims of that token.
Implementation
Install Microsoft.AspNetCore.Authentication.JwtBearer.
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://my-idp.com";
options.Audience = "my-api";
// Critical for security!
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
Authorization Policies
Don’t just check if the user is logged in. Check scopes and permissions using Policies.
services.AddAuthorization(options =>
{
options.AddPolicy("CanDelete", policy =>
policy.RequireClaim("permissions", "delete:resources"));
});
[Authorize(Policy = "CanDelete")]
[HttpDelete("{id}")]
public IActionResult Delete(int id) { ... }
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.