This project demonstrates the implementation of JWT (JSON Web Token) authentication in a .NET 9 minimal API application. It provides a secure way to handle user authentication and protect API endpoints.
- JWT token generation and validation
- Minimal API implementation
- Configuration validation
- HTTP file for API testing
- Role-based authorization
- Environment-specific configuration
- .NET 9 SDK
- Visual Studio 2022 or VS Code
- REST Client extension (for VS Code) if using .http files
- Clone the repository:
git clone https://github.com/yourusername/JwtSample.git
cd JwtSample- Install required NuGet packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt- Configure JWT settings in
appsettings.json:
{
"Jwt": {
"SecretKey": "your-very-long-secret-key-here-min-32-characters",
"Issuer": "your-issuer",
"Audience": "your-audience"
}
}The project includes a .http file for testing the API endpoints.
Example request:
@hostname = http://localhost:5039
### Login to get JWT token
# @name login
POST {{hostname}}/api/auth/login
Content-Type: application/json
{
"email": "[email protected]",
"password": "password123"
}
### Access protected endpoint using the JWT token
GET {{hostname}}/api/auth/protected
Authorization: Bearer {{login.response.body.$.token}}
SecretKey: The key used to sign the JWT token (minimum 32 characters)Issuer: The issuer of the JWT tokenAudience: The intended audience of the JWT token
Create an appsettings.Development.json for development settings:
{
"Jwt": {
"SecretKey": "development-secret-key-that-is-at-least-32-characters",
"Issuer": "development-issuer",
"Audience": "development-audience"
}
}- Store sensitive configuration in user secrets during development:
dotnet user-secrets set "Jwt:SecretKey" "your-secret-key"- Use strong secret keys (minimum 32 characters)
- Implement proper password hashing in production
- Use HTTPS in production
- Set appropriate token expiration times
Authenticates a user and returns a JWT token.
Request:
{
"email": "[email protected]",
"password": "password123"
}Response:
{
"token": "eyJhbGci..."
}A protected endpoint that requires a valid JWT token.
Header:
Authorization: Bearer <token>
Response:
{
"message": "Protected endpoint accessed by [email protected]"
}The application includes validation for:
- Missing or invalid JWT configuration
- Invalid login credentials
- Invalid or expired tokens
- Unauthorized access attempts
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
