A 3-tier ASP.NET Core Web API backed by SQL Server. JWT authentication, role-based and ownership-based authorization, rate limiting, audit logging. Built on the Programming Advices roadmap (Levels 25–26).
- API Layer — Controllers, HTTP endpoints, JWT middleware, Swagger.
- Business Layer — Domain logic, validation. Returns
SaveResult/DeleteResult. - Data Access Layer — ADO.NET, stored procedures against SQL Server.
- Contracts — Shared DTOs crossing layer boundaries.
StudentCredentialsDTOis internal-only and never returned to clients.
Middlewares execute in this order:
UseExceptionHandler— Catches unhandled exceptions from downstream layers.UseHttpsRedirection— Enforces HTTPS.UseCors— AppliesStudentApiCorsPolicy.UseRateLimiter— AppliesAuthLimiterto/loginand/refresh.UseAuthentication— Parses JWT, populatesHttpContext.User.UseAuthorization— Enforces[Authorize], roles, and policies.
Controllers are reached only after all six middlewares pass.
| Method | Route | Access | Notes |
|---|---|---|---|
| POST | /api/Auth/login |
Public | Rate limited: 5 requests/minute per IP |
| POST | /api/Auth/refresh |
Public | Requires valid refresh token. Rate limited: 5 requests/minute per IP |
| POST | /api/Auth/logout |
Public | Requires valid refresh token. Idempotent |
| Method | Route | Access |
|---|---|---|
| GET | /api/Students/All |
🔒 Admin only |
| GET | /api/Students/Passed |
🌐 Public |
| GET | /api/Students/AverageGrade |
🌐 Public |
| GET | /api/Students/{id} |
🔒 Owner (Student) or Admin |
| POST | /api/Students |
🔒 Admin only |
| PUT | /api/Students/{id} |
🔒 Admin only |
| DELETE | /api/Students/{id} |
🔒 Admin only |
- JWT bearer authentication. Issued by
/api/Auth/login, validated by middleware.ClockSkew = TimeSpan.Zeroso tokens expire atexp. - Refresh tokens. 64-byte random, hashed with SHA-256 before storage (BCrypt's 72-byte limit truncates long tokens). Rotated on every refresh. Logout is idempotent.
- Password hashing. BCrypt with automatic salt.
- Role-based authorization.
[Authorize(Roles = "Admin")]on write endpoints and/All. - Ownership authorization.
GET /api/Students/{id}is restricted to the owner (matching JWTNameIdentifier) or Admin, enforced by a customIAuthorizationHandler. - Rate limiting. Fixed window, 5 requests/minute per IP on
/loginand/refresh. 429 responses return a JSON body viaOnRejected. - Global exception handler. Catches all unhandled exceptions, logs them server-side, returns
500 {"error":"An internal error occurred."}. No stack traces or exception messages leak to clients. - Swagger Bearer integration. Authorize button sends the JWT with protected requests.
- Secrets. Connection string and JWT signing key come from configuration (
appsettings.json+appsettings.Development.jsonfor local). Nothing hardcoded.
- .NET 8
- ASP.NET Core Web API
Microsoft.AspNetCore.Authentication.JwtBearerSystem.IdentityModel.Tokens.JwtBCrypt.Net-Next- ADO.NET (
Microsoft.Data.SqlClient) - SQL Server 2022
- Swashbuckle (Swagger)
- Create a database named
StudentsDBin SQL Server. - Run the stored procedures (see
Database/folder). - Create
appsettings.Development.jsonin the API project:{ "ConnectionStrings": { "Default": "Server=localhost;Database=StudentsDB;User Id=YOUR_USER;Password=YOUR_PASSWORD;Encrypt=False;TrustServerCertificate=True;Connection Timeout=30;" }, "JwtSettings": { "SecretKey": "YOUR_LONG_RANDOM_SECRET" } } - Seed at least one admin account:
UPDATE dbo.Students SET Role = 'Admin', Email = '[email protected]', PasswordHash = '<bcrypt hash>' WHERE Id = 1;
- Run:
dotnet run
POST /api/Auth/loginwith valid credentials. Copy theaccessToken.- In Swagger, click Authorize and paste the token.
- Protected endpoints receive the token in the
Authorizationheader. - Test refresh:
POST /api/Auth/refreshwith{ "email": "...", "refreshToken": "..." }. Response contains a new access token and a new refresh token. The old refresh token is invalidated. - Test logout:
POST /api/Auth/logout. A second logout with the same token returns200without touching the DB.
Send six login requests in a row:
for i in {1..6}; do
curl -k -X POST "https://localhost:7217/api/Auth/login" \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"wrong"}'
echo ""
doneExpected:
- Requests 1–5:
401 Invalid credentials - Request 6:
429 {"error":"Too many login attempts. Please try again later."}
Wait 60 seconds. The counter resets.
Log in as a Student:
GET /api/Students/{ownId}→200GET /api/Students/{otherId}→403
Log in as Admin:
GET /api/Students/{anyId}→200
Learning project. Built to demonstrate full 3-tier separation of concerns, JWT authentication with refresh rotation, role-based and ownership-based authorization, rate limiting, and audit logging. Extracted and extended from Level 25 (Introduction to RESTful APIs) and Level 26 (Secure Your APIs) of the Programming Advices roadmap.