Skip to content

Exploration of Authentication Mechanisms in REST APIs using .NET, showcasing multiple styles including API Key, Basic Auth, JWT, Identity-based JWT, and OAuth2 (Duende), all structured with a layered architecture

License

Notifications You must be signed in to change notification settings

VishwamKumar/rest-apis.auth-styles.examples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🌦️ Weather App - REST API Auth Examples

This repository demonstrates various authentication strategies implemented in a simple Weather API using simple Layered Architecture with ASP.NET Core. Each project is built independently to showcase a specific auth mechanism, making it easier for developers to learn and compare implementation patterns.


🛠️ Technologies Used

  • .NET 9.0 - Latest .NET framework
  • ASP.NET Core - Web framework
  • Swagger/OpenAPI (Swashbuckle v9.0.3) - API documentation
  • ASP.NET Core Identity - User management (JwtAuthIdentity project)
  • Entity Framework Core - ORM for database operations (JwtAuthIdentity project)
  • Duende IdentityServer - OAuth2/OpenID Connect server (OAuth2Duende project)
  • JWT Bearer Authentication - Token-based authentication

🔐 Authentication Styles Covered

1. WeatherApp.RestApi.ApiKeyAuth

Authenticates requests using custom API keys passed via headers.

  • Authentication: Custom middleware-based API Key validation
  • Header: X-Api-Key header
  • Configuration: API keys stored in appsettings.json
  • Features: Simple header-based authentication

2. WeatherApp.RestApi.BasicAuth

Implements HTTP Basic Authentication (username/password).

  • Authentication: HTTP Basic Authentication standard
  • Header: Authorization: Basic <base64-encoded-credentials>
  • Configuration: User credentials in appsettings.json
  • Features: Standard HTTP Basic Auth implementation

3. WeatherApp.RestApi.JwtAuth

Uses custom JWT token generation and validation logic.

  • Authentication: JWT Bearer token authentication
  • Token Generation: /api/auth/login endpoint
  • Configuration: JWT settings and user credentials in appsettings.json
  • Features:
    • Custom JWT token generation
    • ASP.NET Core JWT Bearer authentication
    • Token validation with configurable parameters

4. WeatherApp.RestApi.JwtAuthIdentity

Leverages ASP.NET Core Identity for JWT authentication and user management.

  • Authentication: JWT with ASP.NET Core Identity
  • User Management: Entity Framework Core with SQL Server
  • Features:
    • User registration and login
    • Password hashing via Identity
    • JWT token generation with Identity
    • Database-backed user storage
    • Swagger integration with Bearer token support

5. WeatherApp.RestApi.OAuth2Duende

Demonstrates OAuth2/OpenID Connect using Duende IdentityServer.

  • Authentication: OAuth2/OpenID Connect
  • Identity Server: Duende IdentityServer for token issuance
  • Features:
    • Client credentials flow
    • RSA-based token signing
    • In-memory clients and scopes
    • JWT validation with IdentityServer authority
    • Custom API resource configuration

▶️ Getting Started

Prerequisites

  • .NET 9.0 SDK or later
  • Visual Studio 2022, VS Code, or Rider (optional)
  • SQL Server (for JwtAuthIdentity project)
  • For OAuth2Duende: RSA keys configured

Clone the Repository

git clone https://github.com/vishwamkumar/weather-app.rest-apis.layered.git
cd weather-app.rest-apis.layered/src

▶️ Run Any Project

Each project contains its own solution and can be run/tested independently.

cd WeatherApp.RestApi.JwtAuth
dotnet run

Replace JwtAuth with ApiKeyAuth, BasicAuth, JwtAuthIdentity, or OAuth2Duende to run other projects.

Default Ports:

  • HTTP: http://localhost:5000
  • HTTPS: https://localhost:5001

Swagger UI:

  • Available at: http://localhost:5000/swagger (in Development mode)

🧪 Testing APIs

Swagger UI

All projects include Swagger/OpenAPI documentation accessible at:

http://localhost:5000/swagger

You can:

  • Explore API endpoints
  • Test authenticated requests
  • View request/response schemas
  • Configure authentication headers

Test Documentation

Each project includes a Docs/TestMe.md file with:

  • Example API requests
  • Authentication header configurations
  • cURL examples
  • Postman collection references

Quick Test Examples

ApiKeyAuth:

curl -H "X-Api-Key: your-api-key" http://localhost:5000/api/weatherforecast

BasicAuth:

curl -u username:password http://localhost:5000/api/weatherforecast

JwtAuth:

# 1. Get token
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","password":"password1"}'

# 2. Use token
curl -H "Authorization: Bearer <token>" http://localhost:5000/api/weatherforecast

📂 Project Structure

rest-apis.auth-styles.examples/
├── src/
│   ├── WeatherApp.RestApi.ApiKeyAuth/
│   │   ├── Controllers/      # Weather forecast controller
│   │   ├── Middlewares/      # API Key authentication middleware
│   │   ├── Configs/          # API Key configuration
│   │   ├── Dtos/             # Data transfer objects
│   │   └── Program.cs
│   │
│   ├── WeatherApp.RestApi.BasicAuth/
│   │   ├── Controllers/      # Weather forecast controller
│   │   ├── Middlewares/      # Basic authentication middleware
│   │   ├── Configs/          # User credential configuration
│   │   ├── Dtos/             # Data transfer objects
│   │   └── Program.cs
│   │
│   ├── WeatherApp.RestApi.JwtAuth/
│   │   ├── Controllers/      # Auth and weather controllers
│   │   ├── Configs/          # JWT and user credential settings
│   │   ├── Dtos/             # Data transfer objects
│   │   └── Program.cs
│   │
│   ├── WeatherApp.RestApi.JwtAuthIdentity/
│   │   ├── Controllers/      # Auth and weather controllers
│   │   ├── Services/         # Token service and user context
│   │   ├── Configs/          # JWT settings
│   │   ├── Migrations/       # Entity Framework migrations
│   │   ├── Dtos/             # Data transfer objects
│   │   └── Program.cs
│   │
│   └── WeatherApp.RestApi.OAuth2Duende/
│       ├── Controllers/      # Weather forecast controller
│       ├── Providers/        # RSA key provider
│       ├── Configs/          # IdentityServer and JWT settings
│       ├── keys/             # RSA key files
│       ├── Dtos/             # Data transfer objects
│       └── Program.cs

🛡️ Auth Mechanisms Compared

Project Security Mechanism AuthN / AuthZ Provider Header/Token Location
ApiKeyAuth API Key Header-based static key Custom X-Api-Key header
BasicAuth HTTP Basic Username/password Custom Authorization: Basic <base64>
JwtAuth JWT Token-based Custom Authorization: Bearer <token>
JwtAuthIdentity JWT + Identity Token + User management ASP.NET Core Identity Authorization: Bearer <token>
OAuth2Duende OAuth2/OpenID IdentityServer tokens Duende IdentityServer Authorization: Bearer <token>

⚙️ Configuration

ApiKeyAuth

{
  "ApiKeys": [
    {
      "Key": "your-api-key-here",
      "Owner": "ClientName"
    }
  ]
}

BasicAuth

{
  "UserCredentials": [
    {
      "Username": "user1",
      "Password": "password1"
    }
  ]
}

JwtAuth

{
  "JwtSettings": {
    "SecretKey": "your-secret-key-min-32-chars",
    "Issuer": "WeatherApp",
    "Audience": "WeatherAppUsers",
    "ExpiryInMinutes": 60
  },
  "UserCredentials": [
    {
      "Username": "user1",
      "Password": "password1"
    }
  ]
}

JwtAuthIdentity

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=WeatherAppDb;Trusted_Connection=True;"
  },
  "JwtSettings": {
    "SecretKey": "your-secret-key-min-32-chars",
    "Issuer": "WeatherApp",
    "Audience": "WeatherAppUsers",
    "ExpiryInMinutes": 60
  }
}

OAuth2Duende

{
  "JwtSettings": {
    "SecretKey": "key-id-for-rsa",
    "Issuer": "https://localhost:5001",
    "Audience": "WeatherAppApi",
    "ExpiryInMinutes": 60
  },
  "IdentityServerSettings": {
    "ClientId": "WeatherAppClient",
    "ClientSecret": "client-secret",
    "Scopes": [
      {
        "Name": "weather.read",
        "DisplayName": "Weather Read Access"
      }
    ]
  }
}

📝 Key Features

  • Multiple Auth Strategies - 5 different authentication approaches
  • Swagger/OpenAPI - Interactive API documentation
  • Layered Architecture - Clean separation of concerns
  • ASP.NET Core Identity - Full user management (JwtAuthIdentity)
  • OAuth2/OpenID Connect - Industry-standard authentication (OAuth2Duende)
  • Entity Framework Core - Database integration (JwtAuthIdentity)
  • JWT Bearer Authentication - Token-based security
  • Middleware-based Auth - Custom authentication middleware
  • Configuration-driven - Easy to configure via appsettings.json

🔗 Related Projects


👤 Authors

Vishwa Kumar

Vishwa is the primary developer and architect of this example app, responsible for the architecture and implementation of these features.


📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Exploration of Authentication Mechanisms in REST APIs using .NET, showcasing multiple styles including API Key, Basic Auth, JWT, Identity-based JWT, and OAuth2 (Duende), all structured with a layered architecture

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages