This solution demonstrates how to implement a centralized authentication system using Azure Entra ID (formerly Azure AD) for .NET microservices. It includes two services:
- AuthService: Handles authentication and token management
- ProtectedApi: A sample API that requires authentication
- Azure subscription
- Visual Studio 2022 or later
- .NET 8.0 SDK
- Azure CLI (optional)
- Sign in to the Azure Portal
- Navigate to Azure Entra ID
- Register two applications:
- AuthService (Web API)
- ProtectedApi (Web API)
- Configure the following for each application:
- Authentication
- API permissions
- App roles (Admin and User)
- Expose an API (for ProtectedApi)
- Update the
appsettings.json
files in both projects with your Azure Entra ID settings:- TenantId
- ClientId
- ClientSecret (for AuthService only)
- Audience
- Scopes
-
Open the solution in Visual Studio
-
Set both projects as startup projects:
- Right-click on the solution
- Select "Set Startup Projects"
- Choose "Multiple startup projects"
- Set both AuthService and ProtectedApi to "Start"
-
Press F5 to run the solution
GET /api/auth/profile
- Get user profile and claimsGET /api/auth/token
- Get token for downstream API (Admin only)GET /api/auth/validate
- Validate current tokenGET /api/auth/roles
- Get user roles (Admin only)
GET /api/secure
- Get admin-only dataGET /api/secure/user
- Get user dataGET /api/secure/public
- Get public data (no auth required)GET /api/secure/claims
- Get user claims
-
Use Swagger UI:
- AuthService: https://localhost:7001/swagger
- ProtectedApi: https://localhost:7002/swagger
-
Use tools like Postman:
- Get a token from AuthService
- Use the token in the Authorization header for ProtectedApi requests
- Always use HTTPS in production
- Store secrets in Azure Key Vault
- Implement proper error handling
- Use appropriate token lifetimes
- Implement token revocation
- Monitor authentication logs
- Regular security updates
Feel free to submit issues and enhancement requests!
This project is licensed under the MIT License - see the LICENSE file for details.