In modern web development, securing APIs is crucial. This blog explains how to implement a simple yet secure token-based authentication system in a Blazor Server application using ASP.NET Core Web API.
This is especially useful when you donβt want to rely on JWT or external identity providers and need a custom implementation tailored to your app.
π Key Concepts Covered
- Logging in and returning a GUID-based access token
- Storing the token in localStorage (with JS interop)
- Sending the token via headers on future API requests
- Validating the token on the server using a custom authentication handler
- Protecting your API using the
[Authorize]
attribute
βΆοΈ Watch Full Video Tutorial on YouTube
π¦ Custom AuthenticationHandler
public class TokenAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue("X-Access-Token", out var tokenValue))
return Task.FromResult(AuthenticateResult.Fail("Token missing"));
var token = tokenValue.FirstOrDefault();
// Validate token from DB and create claims
...
}
}
π§ Program.cs Setup
builder.Services.AddAuthentication("TokenScheme")
.AddScheme<AuthenticationSchemeOptions, TokenAuthenticationHandler>("TokenScheme", null);
app.UseAuthentication();
app.UseAuthorization();
β
Secure API with [Authorize]
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class UserController : ControllerBase
{
[HttpGet("me")]
public IActionResult Me() => Ok(User.Identity.Name);
}
π― One-to-One .NET Coaching Available
Want to master .NET, ASP.NET Core, Blazor, or prepare for real-world interviews? I offer personalized one-to-one classes that make you industry-ready.