ASP.NET Core Web API Interview Question #75
What are best practices for authentication, authorization, JWT, and API security?
Authentication, Authorization, JWT & API Security Mid-Level Intermediate
Quick Interview Answer
Use a trusted authentication system and validate tokens completely, including signature, issuer, audience, and lifetime. Keep authorization server-side and prefer reusable policies or resource-based checks for meaningful permissions. Apply least privilege and distinguish authentication failures from authorization failures.
Detailed Explanation
Use a trusted authentication system and validate tokens completely, including signature, issuer, audience, and lifetime. Keep authorization server-side and prefer reusable policies or resource-based checks for meaningful permissions. Apply least privilege and distinguish authentication failures from authorization failures.
Require HTTPS, protect credentials and keys, configure CORS narrowly, validate all input, avoid leaking sensitive data, use short-lived access tokens with a deliberate refresh-token strategy, and add controls such as rate limiting where appropriate. Security should be layered across identity, application code, configuration, transport, data access, logging, and deployment infrastructure.
Code Example
[Authorize(Policy = "CanManageProducts")]
[HttpPost]
public async Task<ActionResult<ProductResponse>> Create(
CreateProductRequest request,
CancellationToken token)
{
var product = await _service.CreateAsync(
User, request, token);
return CreatedAtAction(
nameof(GetById),
new { id = product.Id },
product);
}