OAuth2 and JWT (JSON Web Token) are essential for securing modern web applications and APIs. OAuth2 provides authorization capabilities, while JWT ensures secure, stateless authentication. In this guide, we will:
- Set up IdentityServer4 for OAuth2 authentication
- Implement JWT-based authentication and authorization
- Secure APIs with role-based access control (RBAC)
By the end of this tutorial, you will have a fully functional authentication system in a .NET Core application.
1. Set Up IdentityServer4 for OAuth2 Authentication
1.1 Prerequisites
Ensure you have:
- .NET Core SDK (8.0 or latest version)
- Visual Studio or VS Code
- Postman for API testing
1.2 Create a New .NET Core Project
Create an ASP.NET Core Web API:
dotnet new webapi -o AuthDemo
cd AuthDemo
1.3 Install IdentityServer4
IdentityServer4 is an OpenID Connect and OAuth2 framework for .NET Core. Install the required NuGet packages:
dotnet add package IdentityServer4
1.4 Configure IdentityServer4
Modify Program.cs
:
using IdentityServer4.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Configure IdentityServer
builder.Services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(new List<ApiResource>
{
new ApiResource("api", "My API")
})
.AddInMemoryClients(new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedScopes = { "api" }
}
});
var app = builder.Build();
app.UseIdentityServer();
app.Run();
Run the application and verify IdentityServer is working.
2. Implement JWT-Based Authentication and Authorization
2.1 Install JWT Authentication Packages
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
2.2 Configure JWT Authentication
Modify Program.cs
to add JWT authentication:
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5000"; // IdentityServer URL
options.Audience = "api";
});
app.UseAuthentication();
app.UseAuthorization();
2.3 Secure API Endpoints
Modify Controllers/WeatherForecastController.cs
:
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new { Message = "Authenticated API Response" });
}
}
3. Secure APIs with Role-Based Access Control (RBAC)
3.1 Add Roles to IdentityServer
Modify IdentityServer client configuration:
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedScopes = { "api" },
Claims = new List<ClientClaim>
{
new ClientClaim("role", "Admin")
}
}
3.2 Enforce Role-Based Authorization in API
Modify WeatherForecastController.cs
:
[Authorize(Roles = "Admin")]
[HttpGet]
public IActionResult Get()
{
return Ok(new { Message = "Admin Access Granted" });
}
Conclusion
We have successfully implemented OAuth2 and JWT authentication in .NET Core, including:
- Setting up IdentityServer4 for OAuth2 authentication
- Implementing JWT-based authentication and authorization
- Securing APIs with role-based access control (RBAC)
With these configurations, you can now build secure and scalable APIs in .NET Core.