A secure and scalable ASP.NET Core Web API with JWT Authentication and Role-Based Authorization.
- ASP.NET Core 8 Web API
- Entity Framework Core 8
- SQL Server (LocalDB)
- JWT Authentication
- BCrypt Password Hashing
- Swagger UI
ProductsAPI/ ├── Controllers/ │ ├── AuthController.cs │ └── ProductController.cs ├── Models/ │ ├── User.cs │ └── Product.cs ├── DTOs/ │ ├── RegisterDto.cs │ ├── LoginDto.cs │ ├── ProductDto.cs │ └── AuthResponseDto.cs ├── Data/ │ └── ApplicationDbContext.cs ├── Repositories/ │ ├── IAuthRepository.cs │ ├── AuthRepository.cs │ ├── IProductRepository.cs │ └── ProductRepository.cs ├── Services/ │ ├── IAuthService.cs │ ├── AuthService.cs │ ├── IProductService.cs │ └── ProductService.cs ├── Helpers/ │ └── JwtHelper.cs ├── Middleware/ │ └── ExceptionMiddleware.cs ├── appsettings.json └── Program.cs
- Visual Studio 2022
- .NET 8 SDK
- SQL Server
git clone https://github.com/new-git-pix/Products-API.git
Open appsettings.json and update:
"ConnectionStrings": {
"DefaultConnection": "Your SQL Server connection string here"
}Open Package Manager Console and run: Add-Migration InitialCreate Update-Database
Press F5 in Visual Studio Open https://localhost:{port}/swagger
| Field | Value |
|---|---|
| admin@test.com | |
| Password | Admin@123 |
| Role | Admin |
| Field | Value |
|---|---|
| david@gmail.com | |
| Password | David@123 |
| Role | User |
POST /api/auth/register { "username": "admin", "email": "admin@test.com", "password": "Admin@123", "role": "Admin" }
Click Authorize button (top right) Enter: Bearer {paste your token here} Click Authorize then Close
POST /api/auth/login { "email": "admin@test.com", "password": "Admin@123" }
POST /api/auth/login { "email": "david@gmail.com", "password": "David@123" }
| Method | Endpoint | Access |
|---|---|---|
| POST | /api/auth/register | Public |
| POST | /api/auth/login | Public |
| GET | /api/product | Authenticated Users |
| GET | /api/product/{id} | Authenticated Users |
| POST | /api/product | Admin Only |
| PUT | /api/product/{id} | Admin Only |
| DELETE | /api/product/{id} | Admin Only |
| Role | Register | Login | View Products |
|---|---|---|---|
| Guest | ✅ | ✅ | ❌ |
| User | ✅ | ✅ | ✅ |
| Admin | ✅ | ✅ | ✅ |
| Role | Create | Update | Delete |
|---|---|---|---|
| Guest | ❌ | ❌ | ❌ |
| User | ❌ | ❌ | ❌ |
| Admin | ✅ | ✅ | ✅ |
- Passwords are hashed using BCrypt
- JWT tokens expire after 2 hours
- Role based authorization using [Authorize] attribute
- Global exception handling middleware
-
⚠️ Note: In production environment, JWT SecretKey should be stored in Azure Key Vault or Environment Variables, not in appsettings.json
MANJU JOSE