ASP.NET Core 10 + SQL Server + ASP.NET Core Identity + JWT + Refresh Tokens + Role-Based Authorization + Angular
We will upgrade the existing E-Commerce Microservices project into a modern, secure authentication architecture.
This is a practical implementation that you can teach step by step in your .NET classroom.
Technologies
ASP.NET Core 10 Web API
SQL Server
Entity Framework Core 10
ASP.NET Core Identity
JWT Authentication
Refresh Token Rotation
Role-Based Authorization
Ocelot API Gateway
Angular 21
HttpClient and HTTP Interceptors
1. What exactly are we going to build?
Imagine that we are developing an E-Commerce application.
Users can:
Register an account.
Login with email and password.
Receive an access token.
Access protected APIs.
Refresh an expired access token.
Logout and revoke their refresh token.
Administrators can:
Access all users.
Create products.
Delete users.
Access administrator-only APIs.
Customers can:
View products.
Create orders.
View their orders.
Final architecture
ANGULAR 21
|
|
LOGIN / REGISTER
|
v
API GATEWAY
localhost:7000
|
+-------------+-------------+
| |
v v
AUTH SERVICE OTHER SERVICES
Port 6005 |
| |
v +----------+----------+
AuthDb | | |
| v v v
| UserService ProductService OrderService
| | | |
| v v v
| UserDb ProductDb OrderDb
|
+-- ASP.NET Core Identity
|
+-- User Registration
|
+-- Password Hashing
|
+-- Role Management
|
+-- JWT Generation
|
+-- Refresh Token RotationImportant design decision
We will use:
One AuthService to generate JWT tokens.
One common access token for the user's application session.
API Gateway to validate incoming JWT tokens.
Individual microservices to validate JWT tokens independently.
AuthDb to store Identity users, roles and refresh-token records.
Separate databases for UserService, ProductService and OrderService.
Remember: ASP.NET Core Identity manages user accounts, password hashing and roles. JWT is used to authenticate API requests. Refresh tokens are used to obtain new access tokens without asking the user to log in again.
2. Understand the complete authentication flow
Before writing code, understand this flow.
Step 1: Registration
- Angular sends name, email and password.
- AuthService receives registration request.
- ASP.NET Core Identity hashes the password.
- User details are stored in AuthDb.
Step 2: Login
- Angular sends email and password.
- AuthService validates credentials using UserManager.
- AuthService generates an access JWT.
- AuthService creates a refresh token and stores its hash in AuthDb.
- Angular receives the access token. The refresh token is placed in a secure HttpOnly cookie.
Step 3: Access protected APIs
- Angular sends the access token in Authorization header.
- API Gateway validates the JWT.
- Gateway forwards the request to the relevant microservice.
- Microservice independently validates the JWT and checks permissions.
Step 4: Refresh token
- When access token expires, Angular calls refresh endpoint.
- Browser automatically sends the HttpOnly refresh cookie.
- AuthService validates the refresh token.
- Old refresh token is revoked and a new refresh token is issued.
- New access token is returned.
Step 5: Logout
AuthService revokes the refresh token and clears the refresh cookie.
3. Create AuthService project
Open terminal in your existing EcommerceMicroservices solution.
dotnet new webapi -n AuthService
dotnet sln add AuthServiceInstall required packages:
dotnet add AuthService package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 10.0.0
dotnet add AuthService package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.0
dotnet add AuthService package Microsoft.EntityFrameworkCore.Design --version 10.0.0
dotnet add AuthService package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.0Use the latest compatible .NET 10 servicing versions rather than downgrading an existing project.
Install EF Core tools if required:
dotnet tool install --global dotnet-efYour solution will now look like:
EcommerceMicroservices
│
├── AuthService
│
├── ApiGateway
│
├── UserService
│
├── ProductService
│
└── OrderService4. Create AuthService database
We will use a separate SQL Server database:
SQL Server
|
+---- AuthDb
| |
| +---- AspNetUsers
| +---- AspNetRoles
| +---- AspNetUserRoles
| +---- AspNetUserClaims
| +---- AspNetUserLogins
| +---- AspNetUserTokens
| +---- RefreshTokens
|
+---- UserDb
+---- ProductDb
+---- OrderDbAuthService/appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=AuthDb;Trusted_Connection=True;TrustServerCertificate=True;"
},
"Jwt": {
"Issuer": "EcommerceAuthService",
"Audience": "EcommerceAPI",
"Secret": "REPLACE_WITH_A_LONG_RANDOM_SECRET_OF_AT_LEAST_32_BYTES",
"AccessTokenMinutes": 15,
"RefreshTokenDays": 7
},
"AllowedHosts": "*"
}For production, keep the secret in a secure secret manager, not in appsettings.json or source control.
5. Create ApplicationUser model
ASP.NET Core Identity already provides a user model called IdentityUser.
However, we want to add extra properties such as FullName.
Create:
Models/ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
namespace AuthService.Models;
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}Why inherit from IdentityUser?
Because IdentityUser already provides:
Property | Purpose |
|---|---|
Id | Unique user ID |
UserName | Username |
Email address | |
PasswordHash | Hashed password |
PhoneNumber | Mobile number |
EmailConfirmed | Email verification |
LockoutEnabled | Account lockout |
AccessFailedCount | Failed login attempts |
We don't need to manually implement password hashing, password verification or account lockout.
6. Create AuthDbContext
Create folder:
Data/AuthDbContext.cs
using AuthService.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace AuthService.Data;
public class AuthDbContext : IdentityDbContext<ApplicationUser>
{
public AuthDbContext(
DbContextOptions<AuthDbContext> options)
: base(options)
{
}
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<RefreshToken>(entity =>
{
entity.HasKey(x => x.Id);
entity.HasIndex(x => x.TokenHash)
.IsUnique();
entity.Property(x => x.TokenHash)
.HasMaxLength(64)
.IsRequired();
entity.HasOne(x => x.User)
.WithMany()
.HasForeignKey(x => x.UserId)
.OnDelete(DeleteBehavior.Cascade);
});
}
}Notice that base.OnModelCreating(builder) is important. It configures the tables required by ASP.NET Core Identity.
7. Create RefreshToken model
Access tokens should have a short lifetime. Refresh tokens allow users to continue their sessions without logging in repeatedly.
Create:
Models/RefreshToken.cs
namespace AuthService.Models;
public class RefreshToken
{
public int Id { get; set; }
public string UserId { get; set; } = string.Empty;
// Store SHA-256 hash, never the original refresh token
public string TokenHash { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime ExpiresAt { get; set; }
public DateTime? RevokedAt { get; set; }
public string? ReplacedByTokenHash { get; set; }
public ApplicationUser User { get; set; } = null!;
public bool IsActive =>
RevokedAt == null &&
DateTime.UtcNow < ExpiresAt;
}Why do we need RefreshToken table?
Example:
Token | Expiry | Status |
|---|---|---|
RefreshToken A | 7 days | Revoked |
RefreshToken B | 7 days | Active |
When the user refreshes the session, the old token is revoked and a new one is created.
This is called Refresh Token Rotation.
8. Create DTOs
DTO means Data Transfer Object.
We use DTOs to transfer data between Angular and AuthService without exposing database entities.
Create folder DTOs.
DTOs/RegisterRequest.cs
using System.ComponentModel.DataAnnotations;
namespace AuthService.DTOs;
public class RegisterRequest
{
[Required]
[StringLength(100)]
public string FullName { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
[MinLength(8)]
public string Password { get; set; } = string.Empty;
}DTOs/LoginRequest.cs
using System.ComponentModel.DataAnnotations;
namespace AuthService.DTOs;
public class LoginRequest
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
}DTOs/AuthResponse.cs
namespace AuthService.DTOs;
public class AuthResponse
{
public string AccessToken { get; set; } = string.Empty;
public DateTime ExpiresAt { get; set; }
public string FullName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public IList<string> Roles { get; set; } = [];
}We deliberately do not return the refresh token in the JSON response. It will be sent as an HttpOnly cookie.
9. Create JWT Token Service
Create:
Services/JwtTokenService.cs
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AuthService.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
namespace AuthService.Services;
public class JwtTokenService
{
private readonly IConfiguration _configuration;
private readonly UserManager<ApplicationUser> _userManager;
public JwtTokenService(
IConfiguration configuration,
UserManager<ApplicationUser> userManager)
{
_configuration = configuration;
_userManager = userManager;
}
public async Task<(string Token, DateTime ExpiresAt)>
GenerateTokenAsync(ApplicationUser user)
{
var jwt = _configuration.GetSection("Jwt");
var secret = jwt["Secret"]
?? throw new InvalidOperationException("JWT secret missing.");
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(secret));
var credentials = new SigningCredentials(
key,
SecurityAlgorithms.HmacSha256);
var roles = await _userManager.GetRolesAsync(user);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id),
new(JwtRegisteredClaimNames.Email, user.Email ?? ""),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(ClaimTypes.Name, user.FullName)
};
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var expiresAt = DateTime.UtcNow.AddMinutes(
Convert.ToDouble(jwt["AccessTokenMinutes"] ?? "15"));
var token = new JwtSecurityToken(
issuer: jwt["Issuer"],
audience: jwt["Audience"],
claims: claims,
notBefore: DateTime.UtcNow,
expires: expiresAt,
signingCredentials: credentials
);
return (
new JwtSecurityTokenHandler().WriteToken(token),
expiresAt
);
}
}Understand JWT structure
A JWT has three parts:
HEADER.PAYLOAD.SIGNATUREExample decoded payload:
{
"sub": "a-user-id",
"email": "shiva@example.com",
"role": [
"Customer"
],
"exp": 1790000000,
"iss": "EcommerceAuthService",
"aud": "EcommerceAPI"
}JWT is signed, not encrypted. Never put passwords or sensitive personal data inside its payload.
10. Create Refresh Token Service
Create:
Services/RefreshTokenService.cs
using System.Security.Cryptography;
using System.Text;
using AuthService.Data;
using AuthService.Models;
using Microsoft.EntityFrameworkCore;
namespace AuthService.Services;
public class RefreshTokenService
{
private readonly AuthDbContext _context;
private readonly IConfiguration _configuration;
public RefreshTokenService(
AuthDbContext context,
IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
public async Task<(string RawToken, RefreshToken Entity)>
CreateAsync(ApplicationUser user)
{
var rawToken = Convert.ToBase64String(
RandomNumberGenerator.GetBytes(64));
var tokenHash = HashToken(rawToken);
var days = Convert.ToDouble(
_configuration["Jwt:RefreshTokenDays"] ?? "7");
var entity = new RefreshToken
{
UserId = user.Id,
TokenHash = tokenHash,
CreatedAt = DateTime.UtcNow,
ExpiresAt = DateTime.UtcNow.AddDays(days)
};
_context.RefreshTokens.Add(entity);
await _context.SaveChangesAsync();
return (rawToken, entity);
}
public static string HashToken(string token)
{
var bytes = SHA256.HashData(
Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes);
}
public async Task<RefreshToken?> FindActiveAsync(string rawToken)
{
var hash = HashToken(rawToken);
return await _context.RefreshTokens
.Include(x => x.User)
.FirstOrDefaultAsync(x =>
x.TokenHash == hash &&
x.RevokedAt == null &&
x.ExpiresAt > DateTime.UtcNow);
}
public async Task RevokeAsync(
RefreshToken token,
string? replacementHash = null)
{
token.RevokedAt = DateTime.UtcNow;
token.ReplacedByTokenHash = replacementHash;
await _context.SaveChangesAsync();
}
}Why hash the refresh token?
Suppose somebody accesses your AuthDb database.
If you store the original refresh token, that person might use it to obtain a new access token.
Instead:
Original Refresh Token
|
v
SHA-256
|
v
Token Hash
|
v
AuthDbThe browser gets the original token through its secure cookie, while AuthDb stores only its hash.
11. Configure ASP.NET Core Identity and JWT
This is the most important configuration step.
Open:
AuthService/Program.cs
Replace its contents with:
using System.Text;
using AuthService.Data;
using AuthService.Models;
using AuthService.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// Controllers
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// SQL Server
builder.Services.AddDbContext<AuthDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
// ASP.NET Core Identity
builder.Services
.AddIdentityCore<ApplicationUser>(options =>
{
options.Password.RequiredLength = 8;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan =
TimeSpan.FromMinutes(15);
options.User.RequireUniqueEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AuthDbContext>()
.AddSignInManager();
// JWT
var jwt = builder.Configuration.GetSection("Jwt");
var secret = jwt["Secret"]
?? throw new InvalidOperationException("JWT secret missing.");
var signingKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(secret));
builder.Services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme =
JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme =
JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwt["Issuer"],
ValidateAudience = true,
ValidAudience = jwt["Audience"],
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ClockSkew = TimeSpan.Zero
};
});
// Authorization
builder.Services.AddAuthorization();
// Application services
builder.Services.AddScoped<JwtTokenService>();
builder.Services.AddScoped<RefreshTokenService>();
builder.Services.AddHealthChecks();
var app = builder.Build();
// Database initialization and role seeding
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AuthDbContext>();
await db.Database.MigrateAsync();
var roleManager = scope.ServiceProvider
.GetRequiredService<RoleManager<IdentityRole>>();
string[] roles = { "Admin", "Customer", "Manager" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(
new IdentityRole(role));
}
}
}
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHealthChecks("/health");
app.Run();What does this configuration do?
Code | Purpose |
|---|---|
AddIdentityCore | Configures Identity |
AddRoles | Enables role management |
AddEntityFrameworkStores | Connects Identity to SQL Server |
AddSignInManager | Provides sign-in functionality |
AddAuthentication | Enables authentication |
AddJwtBearer | Enables JWT validation |
AddAuthorization | Enables access policies |
AddScoped | Registers application services |
We use AddIdentityCore because we are building a JWT-based API rather than a traditional cookie-based MVC application.
12. Create AuthController
Now we will create the actual API endpoints:
Method | Endpoint | Purpose |
|---|---|---|
POST |
| Register new user |
POST |
| Login and generate JWT |
POST |
| Generate new access token |
POST |
| Revoke refresh token |
GET |
| Get logged-in user |
Create:
Controllers/AuthController.cs
using AuthService.Data;
using AuthService.DTOs;
using AuthService.Models;
using AuthService.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AuthService.Controllers;
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly JwtTokenService _jwtService;
private readonly RefreshTokenService _refreshService;
private readonly AuthDbContext _context;
private readonly IConfiguration _configuration;
public AuthController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
JwtTokenService jwtService,
RefreshTokenService refreshService,
AuthDbContext context,
IConfiguration configuration)
{
_userManager = userManager;
_signInManager = signInManager;
_jwtService = jwtService;
_refreshService = refreshService;
_context = context;
_configuration = configuration;
}
// ===================================
// 1. REGISTER
// ===================================
[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> Register(
RegisterRequest request)
{
var existingUser = await _userManager
.FindByEmailAsync(request.Email);
if (existingUser != null)
return BadRequest("Email already registered.");
var user = new ApplicationUser
{
FullName = request.FullName,
Email = request.Email,
UserName = request.Email
};
var result = await _userManager
.CreateAsync(user, request.Password);
if (!result.Succeeded)
{
return BadRequest(new
{
Errors = result.Errors.Select(x => x.Description)
});
}
// All public registrations receive Customer role.
await _userManager.AddToRoleAsync(user, "Customer");
return Ok(new
{
Message = "Registration successful.",
UserId = user.Id,
user.FullName,
user.Email
});
}
// ===================================
// 2. LOGIN
// ===================================
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login(
LoginRequest request)
{
var user = await _userManager
.FindByEmailAsync(request.Email);
if (user == null)
return Unauthorized("Invalid email or password.");
var result = await _signInManager
.CheckPasswordSignInAsync(
user,
request.Password,
lockoutOnFailure: true);
if (!result.Succeeded)
return Unauthorized("Invalid email or password.");
var (accessToken, expiresAt) =
await _jwtService.GenerateTokenAsync(user);
var (refreshToken, refreshEntity) =
await _refreshService.CreateAsync(user);
SetRefreshCookie(
refreshToken,
refreshEntity.ExpiresAt);
var roles = await _userManager.GetRolesAsync(user);
return Ok(new AuthResponse
{
AccessToken = accessToken,
ExpiresAt = expiresAt,
FullName = user.FullName,
Email = user.Email!,
Roles = roles
});
}
// ===================================
// 3. REFRESH TOKEN
// ===================================
[AllowAnonymous]
[HttpPost("refresh")]
public async Task<IActionResult> Refresh()
{
if (!Request.Cookies.TryGetValue(
"refreshToken", out var oldRawToken))
{
return Unauthorized("Refresh token missing.");
}
var oldToken = await _refreshService
.FindActiveAsync(oldRawToken);
if (oldToken == null)
{
ClearRefreshCookie();
return Unauthorized("Invalid or expired refresh token.");
}
await using var transaction =
await _context.Database.BeginTransactionAsync();
try
{
var (newAccessToken, expiresAt) =
await _jwtService.GenerateTokenAsync(oldToken.User);
var (newRawToken, newEntity) =
await _refreshService.CreateAsync(oldToken.User);
await _refreshService.RevokeAsync(
oldToken,
newEntity.TokenHash);
await transaction.CommitAsync();
SetRefreshCookie(
newRawToken,
newEntity.ExpiresAt);
var roles = await _userManager
.GetRolesAsync(oldToken.User);
return Ok(new AuthResponse
{
AccessToken = newAccessToken,
ExpiresAt = expiresAt,
FullName = oldToken.User.FullName,
Email = oldToken.User.Email!,
Roles = roles
});
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
// ===================================
// 4. LOGOUT
// ===================================
[AllowAnonymous]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
if (Request.Cookies.TryGetValue(
"refreshToken", out var rawToken))
{
var token = await _refreshService
.FindActiveAsync(rawToken);
if (token != null)
{
await _refreshService.RevokeAsync(token);
}
}
ClearRefreshCookie();
return Ok(new
{
Message = "Logged out successfully."
});
}
// ===================================
// 5. GET LOGGED-IN USER
// ===================================
[Authorize]
[HttpGet("me")]
public async Task<IActionResult> Me()
{
var userId = _userManager.GetUserId(User);
if (userId == null)
return Unauthorized();
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
return Unauthorized();
return Ok(new
{
user.Id,
user.FullName,
user.Email,
Roles = await _userManager.GetRolesAsync(user)
});
}
// ===================================
// COOKIE HELPERS
// ===================================
private void SetRefreshCookie(
string token,
DateTime expiresAt)
{
Response.Cookies.Append(
"refreshToken",
token,
new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Expires = expiresAt,
Path = "/auth"
});
}
private void ClearRefreshCookie()
{
Response.Cookies.Delete(
"refreshToken",
new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Path = "/auth"
});
}
}Important explanation: HttpOnly cookie
Why are we not storing the refresh token in Angular localStorage?
Because JavaScript can access localStorage. If an attacker manages to execute malicious JavaScript in your application, they may steal tokens.
An HttpOnly cookie cannot be read through JavaScript.
Storage | Access token | Refresh token |
|---|---|---|
Angular memory | Yes | No |
LocalStorage | Avoid | Avoid |
HttpOnly cookie | Optional | Recommended |
For this implementation, Angular keeps the short-lived access token in memory and the browser manages the refresh token cookie.
The cookie must be used over HTTPS. For cross-site deployments, configure SameSite=None; Secure and implement CSRF protection.
13. Create the SQL Server Database
Open terminal inside AuthService:
dotnet ef migrations add InitialIdentity
dotnet ef database updateThis creates AuthDb with Identity tables and your custom RefreshTokens table.
Your database will look like:
Important Identity tables:
Table | Description |
|---|---|
AspNetUsers | User account information |
AspNetRoles | Admin, Customer, Manager |
AspNetUserRoles | User-role relationship |
AspNetUserClaims | User-specific claims |
AspNetRoleClaims | Role-specific claims |
AspNetUserLogins | External login information |
AspNetUserTokens | Identity token information |
RefreshTokens | Our custom refresh token table |
14. Create Admin User
We should never allow someone to register as Admin through the public registration API.
For a classroom demonstration, seed the initial Admin account using configuration.
Add the following to your development user secrets:
dotnet user-secrets init --project AuthService
dotnet user-secrets set "AdminSeed:Email" "admin@example.com" --project AuthService
dotnet user-secrets set "AdminSeed:Password" "ReplaceWithAStrongPassword123!" --project AuthServiceAfter role creation in the Program.cs database initialization block, add:
var userManager = scope.ServiceProvider
.GetRequiredService<UserManager<ApplicationUser>>();
var adminEmail = builder.Configuration["AdminSeed:Email"];
var adminPassword = builder.Configuration["AdminSeed:Password"];
if (!string.IsNullOrWhiteSpace(adminEmail) &&
!string.IsNullOrWhiteSpace(adminPassword))
{
var admin = await userManager.FindByEmailAsync(adminEmail);
if (admin == null)
{
admin = new ApplicationUser
{
FullName = "System Administrator",
Email = adminEmail,
UserName = adminEmail,
EmailConfirmed = true
};
var result = await userManager.CreateAsync(
admin,
adminPassword);
if (!result.Succeeded)
{
throw new InvalidOperationException(
string.Join(", ", result.Errors.Select(x => x.Description)));
}
}
if (!await userManager.IsInRoleAsync(admin, "Admin"))
{
await userManager.AddToRoleAsync(admin, "Admin");
}
}Now your database has an administrator account.
15. Add Role-Based Authorization
Suppose we have three roles:
Admin
Customer
ManagerCreate a new controller in UserService:
Controllers/AdminController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace UserService.Controllers;
[ApiController]
[Route("api/admin")]
[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
[HttpGet("dashboard")]
public IActionResult Dashboard()
{
return Ok(new
{
Message = "Welcome to Admin Dashboard",
User = User.Identity?.Name
});
}
}For a Customer-only API:
[Authorize(Roles = "Customer")]
[HttpGet("my-orders")]
public IActionResult GetMyOrders()
{
return Ok("Customer orders");
}For multiple roles:
[Authorize(Roles = "Admin,Manager")]
[HttpGet("reports")]
public IActionResult GetReports()
{
return Ok("Admin and Manager reports");
}Understand authorization
User | Admin Dashboard | Products | Customer Orders |
|---|---|---|---|
Admin | Allowed | Allowed | Depends on policy |
Manager | Denied | Allowed | Depends on policy |
Customer | Denied | Allowed | Allowed |
A role is not a substitute for ownership checks. For example, a Customer should only see their own orders. Your OrderService must check the authenticated user's ID against the order owner.
16. Configure JWT in API Gateway
Now AuthService generates JWT, but API Gateway must validate it.
Install package:
dotnet add ApiGateway package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.0ApiGateway/appsettings.json
Use the same JWT configuration as AuthService for this HMAC implementation.
{
"Jwt": {
"Issuer": "EcommerceAuthService",
"Audience": "EcommerceAPI",
"Secret": "REPLACE_WITH_A_LONG_RANDOM_SECRET_OF_AT_LEAST_32_BYTES"
}
}ApiGateway/Program.cs
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile(
"ocelot.json",
optional: false,
reloadOnChange: true);
// CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AngularPolicy", policy =>
{
policy
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
// JWT
var jwt = builder.Configuration.GetSection("Jwt");
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwt["Secret"]!));
builder.Services
.AddAuthentication()
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwt["Issuer"],
ValidateAudience = true,
ValidAudience = jwt["Audience"],
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization();
builder.Services.AddOcelot();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseCors("AngularPolicy");
app.UseAuthentication();
app.UseAuthorization();
await app.UseOcelot();
app.Run();Important
The API Gateway must be accessed over HTTPS for our Secure refresh cookie to work.
Configure the HTTPS port in the Gateway launch profile and trust the local development certificate:
dotnet dev-certs https --trust17. Update Ocelot Configuration
We need two types of routes:
Public routes: Registration, Login and Refresh.
Protected routes: Users, Products and Orders.
Create/update ApiGateway/ocelot.json:
{
"Routes": [
{
"UpstreamPathTemplate": "/auth/{everything}",
"UpstreamHttpMethod": ["GET", "POST"],
"DownstreamPathTemplate": "/api/auth/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6005
}
]
},
{
"UpstreamPathTemplate": "/users/{everything}",
"UpstreamHttpMethod": ["GET", "POST", "PUT", "DELETE"],
"DownstreamPathTemplate": "/api/users/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6001
}
],
"AuthenticationOptions": {
"AuthenticationProviderKeys": ["Bearer"],
"AllowedScopes": []
}
},
{
"UpstreamPathTemplate": "/products/{everything}",
"UpstreamHttpMethod": ["GET", "POST", "PUT", "DELETE"],
"DownstreamPathTemplate": "/api/products/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6002
}
],
"AuthenticationOptions": {
"AuthenticationProviderKeys": ["Bearer"],
"AllowedScopes": []
}
},
{
"UpstreamPathTemplate": "/orders/{everything}",
"UpstreamHttpMethod": ["GET", "POST", "PUT", "DELETE"],
"DownstreamPathTemplate": "/api/orders/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6003
}
],
"AuthenticationOptions": {
"AuthenticationProviderKeys": ["Bearer"],
"AllowedScopes": []
}
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7000"
}
}
This is a simple classroom route configuration. If you also expose /users or /products without an ID, add corresponding exact routes because {everything} is intended for paths with a following segment.
Notice that AuthService routes do not contain AuthenticationOptions. Therefore, users can register and log in without already having a token.
18. Configure JWT in Every Microservice
This is an important enterprise practice.
Even though API Gateway validates the JWT, each microservice should independently validate it.
Install the JWT package in each service:
dotnet add UserService package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.0
dotnet add ProductService package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.0
dotnet add OrderService package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.0Add the same issuer, audience and development signing secret to their configuration.
For example, UserService Program.cs:
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var jwt = builder.Configuration.GetSection("Jwt");
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwt["Secret"]!));
builder.Services
.AddAuthentication(
JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwt["Issuer"],
ValidateAudience = true,
ValidAudience = jwt["Audience"],
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization();Add middleware in the correct order:
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();Repeat this configuration in ProductService and OrderService.
For production, replace the shared HMAC secret with asymmetric signing. AuthService signs using a private key, while Gateway and services validate using a public key. This avoids distributing a token-signing secret to every service.
19. Test Authentication Using Postman
Before integrating Angular, test all authentication APIs.
Assume the API Gateway is running at:
https://localhost:7000
Test 1: Register User
/auth/registerPOST https://localhost:7000/auth/register
Content-Type: application/jsonRequest body:
{
"fullName": "Shiva Gautam",
"email": "shiva@example.com",
"password": "Shiva@12345"
}Expected response:
{
"message": "Registration successful.",
"userId": "generated-user-id",
"fullName": "Shiva Gautam",
"email": "shiva@example.com"
}Test 2: Login
/auth/loginPOST https://localhost:7000/auth/loginRequest body:
{
"email": "shiva@example.com",
"password": "Shiva@12345"
}Expected response:
{
"accessToken": "eyJhbGciOiJIUzI1NiIs...",
"expiresAt": "2026-11-23T15:00:00Z",
"fullName": "Shiva Gautam",
"email": "shiva@example.com",
"roles": [
"Customer"
]
}Postman should also receive a Set-Cookie response header for the refresh token.
Test 3: Access UserService
/usersGET https://localhost:7000/users
Authorization: Bearer YOUR_ACCESS_TOKENTest 4: Refresh Token
/auth/refreshPOST https://localhost:7000/auth/refreshPostman should automatically send the refresh cookie saved from login.
The response contains a new access token and a replacement refresh cookie.
Test 5: Logout
/auth/logoutPOST https://localhost:7000/auth/logoutThe refresh token will be revoked and its cookie cleared.
20. Angular 21 Integration with API Gateway
Now we will connect our Angular frontend with the .NET microservices architecture.
Create Angular application:
ng new ecommerce-ui --routing --style=scss
cd ecommerce-uiWe will use modern Angular standalone architecture.
Angular project structure
src/app
│
├── core
│ ├── services
│ │ └── auth.service.ts
│ │
│ ├── interceptors
│ │ └── auth.interceptor.ts
│ │
│ └── guards
│ ├── auth.guard.ts
│ └── role.guard.ts
│
├── pages
│ ├── login
│ │ └── login.component.ts
│ │
│ ├── register
│ │ └── register.component.ts
│ │
│ └── dashboard
│ └── dashboard.component.ts
│
├── app.config.ts
└── app.routes.ts20.1 Create AuthService
This service communicates with our API Gateway.
Create:
core/services/auth.service.ts
import { Injectable, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, tap, map, catchError, of, shareReplay, finalize } from 'rxjs';
export interface LoginRequest {
email: string;
password: string;
}
export interface RegisterRequest {
fullName: string;
email: string;
password: string;
}
export interface AuthResponse {
accessToken: string;
expiresAt: string;
fullName: string;
email: string;
roles: string[];
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
private readonly apiUrl = 'https://localhost:7000/auth';
// Access token stays in application memory
accessToken = signal<string | null>(null);
currentUser = signal<AuthResponse | null>(null);
private refreshRequest$: Observable<string> | null = null;
constructor(private http: HttpClient) {}
// REGISTER
register(data: RegisterRequest): Observable<any> {
return this.http.post(
`${this.apiUrl}/register`,
data
);
}
// LOGIN
login(data: LoginRequest): Observable<AuthResponse> {
return this.http.post<AuthResponse>(
`${this.apiUrl}/login`,
data,
{ withCredentials: true }
).pipe(
tap(response => this.setSession(response))
);
}
// REFRESH TOKEN
refreshSession(): Observable<string> {
if (this.refreshRequest$) {
return this.refreshRequest$;
}
this.refreshRequest$ = this.http.post<AuthResponse>(
`${this.apiUrl}/refresh`,
{},
{ withCredentials: true }
).pipe(
tap(response => this.setSession(response)),
map(response => response.accessToken),
finalize(() => {
this.refreshRequest$ = null;
}),
shareReplay(1)
);
return this.refreshRequest$;
}
// LOGOUT
logout(): Observable<any> {
return this.http.post(
`${this.apiUrl}/logout`,
{},
{ withCredentials: true }
).pipe(
tap(() => this.clearSession()),
catchError(error => {
this.clearSession();
throw error;
})
);
}
// SAVE SESSION
private setSession(response: AuthResponse): void {
this.accessToken.set(response.accessToken);
this.currentUser.set(response);
}
// CLEAR SESSION
clearSession(): void {
this.accessToken.set(null);
this.currentUser.set(null);
}
// ROLE CHECK
hasRole(role: string): boolean {
return this.currentUser()?.roles.includes(role) ?? false;
}
isLoggedIn(): boolean {
return this.accessToken() !== null;
}
}Understand Angular Signals
We are using:
accessToken = signal<string | null>(null);A signal is Angular's reactive state-management mechanism.
When the token changes, components reading that signal can react to the new value.
Unlike localStorage, this access token is kept only in application memory. When the page reloads, Angular can request a new access token using the HttpOnly refresh cookie.
20.2 Create HTTP Interceptor
We don't want to manually add the JWT token to every API request.
Instead, we create one common interceptor.
Create:
core/interceptors/auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { catchError, switchMap, throwError } from 'rxjs';
export const authInterceptor: HttpInterceptorFn =
(req, next) => {
const authService = inject(AuthService);
const token = authService.accessToken();
// Add JWT token to outgoing API request
const authReq = token
? req.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
})
: req;
return next(authReq).pipe(
catchError(error => {
const isRefreshRequest =
req.url.includes('/auth/refresh');
const isLoginRequest =
req.url.includes('/auth/login');
const isRegisterRequest =
req.url.includes('/auth/register');
const isLogoutRequest =
req.url.includes('/auth/logout');
// Refresh token when access token expires
if (
error.status === 401 &&
!isRefreshRequest &&
!isLoginRequest &&
!isRegisterRequest &&
!isLogoutRequest
) {
return authService.refreshSession().pipe(
switchMap(newToken => {
const retryRequest = req.clone({
setHeaders: {
Authorization: `Bearer ${newToken}`
}
});
return next(retryRequest);
}),
catchError(refreshError => {
authService.clearSession();
return throwError(() => refreshError);
})
);
}
return throwError(() => error);
})
);
};What does this interceptor do?
Angular HTTP Request
|
v
HTTP Interceptor
|
v
Access Token Available?
|
v
Authorization: Bearer JWT
|
v
API Gateway
|
v
Response Received
|
v
Is Status 401?
/ \
No Yes
| |
Return Refresh Token
Response |
v
New Access Token
|
v
Retry Original APIThis example automatically retries a failed request after a successful refresh.
20.3 Register Interceptor in app.config.ts
Open:
app.config.ts
import { ApplicationConfig, inject, provideAppInitializer } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { firstValueFrom, catchError, of } from 'rxjs';
import { authInterceptor } from './core/interceptors/auth.interceptor';
import { AuthService } from './core/services/auth.service';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withInterceptors([
authInterceptor
])
),
provideAppInitializer(() => {
const authService = inject(AuthService);
// Restore session after browser refresh
return firstValueFrom(
authService.refreshSession().pipe(
catchError(() => of(null))
)
);
})
]
};This initializer attempts to restore the user's session when Angular starts.
If the refresh cookie is invalid or expired, the user remains logged out.
20.4 Create Login Component
Create:
pages/login/login.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../../core/services/auth.service';
@Component({
selector: 'app-login',
standalone: true,
imports: [
CommonModule,
FormsModule
],
template: `
<div class="login-container">
<h2>E-Commerce Login</h2>
<form (ngSubmit)="login()">
<input
type="email"
name="email"
[(ngModel)]="email"
placeholder="Email"
required
/>
<input
type="password"
name="password"
[(ngModel)]="password"
placeholder="Password"
required
/>
<button type="submit" [disabled]="loading">
{{ loading ? 'Logging in...' : 'Login' }}
</button>
<p>{{ message }}</p>
</form>
</div>
`,
styles: [`
.login-container {
max-width: 400px;
margin: 80px auto;
padding: 30px;
border: 1px solid #ddd;
border-radius: 10px;
}
input {
width: 100%;
padding: 12px;
margin: 10px 0;
box-sizing: border-box;
}
button {
width: 100%;
padding: 12px;
cursor: pointer;
}
`]
})
export class LoginComponent {
email = '';
password = '';
message = '';
loading = false;
constructor(
private authService: AuthService,
private router: Router
) {}
login(): void {
this.loading = true;
this.authService.login({
email: this.email,
password: this.password
}).subscribe({
next: () => {
this.loading = false;
this.router.navigate(['/dashboard']);
},
error: () => {
this.loading = false;
this.message = 'Invalid email or password';
}
});
}
}20.5 Create Authentication Guard
Create:
core/guards/auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
export const authGuard: CanActivateFn = () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login']);
};20.6 Create Role Guard
Create:
core/guards/role.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
export const roleGuard = (requiredRole: string): CanActivateFn => {
return () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.hasRole(requiredRole)) {
return true;
}
return router.createUrlTree(['/dashboard']);
};
};Remember: Angular guards improve navigation and user experience, but they are not security boundaries. The backend must always enforce the actual authorization rules.
20.7 Create Dashboard Component
pages/dashboard/dashboard.component.ts
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { AuthService } from '../../core/services/auth.service';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [CommonModule],
template: `
<h1>Welcome to E-Commerce Dashboard</h1>
<div *ngIf="auth.currentUser() as user">
<h3>{{ user.fullName }}</h3>
<p>{{ user.email }}</p>
<p>Roles: {{ user.roles.join(', ') }}</p>
</div>
<button (click)="logout()">Logout</button>
`
})
export class DashboardComponent {
auth = inject(AuthService);
private router = inject(Router);
logout(): void {
this.auth.logout().subscribe({
next: () => {
this.router.navigate(['/login']);
}
});
}
}20.8 Configure Angular Routes
Open:
app.routes.ts
import { Routes } from '@angular/router';
import { LoginComponent } from './pages/login/login.component';
import { DashboardComponent } from './pages/dashboard/dashboard.component';
import { authGuard } from './core/guards/auth.guard';
import { roleGuard } from './core/guards/role.guard';
export const routes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [authGuard]
},
{
path: 'admin',
component: DashboardComponent,
canActivate: [
authGuard,
roleGuard('Admin')
]
},
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
}
];21. Configure Angular HTTPS and CORS
Because our refresh token cookie has Secure = true, both Angular and API Gateway should run on HTTPS during development.
Run Angular:
ng serve --ssl --port 4200Update the API Gateway CORS configuration:
builder.Services.AddCors(options =>
{
options.AddPolicy("AngularPolicy", policy =>
{
policy
.WithOrigins("https://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});Trust your development certificates and open the Angular application:
Type Angular localhost://4000API Gateway:
Open API GatewayYou may need to trust Angular's development certificate as well. Do not bypass certificate validation in production.
22. Complete Final Project Structure
Your final project should look like this:
EcommerceMicroservices
AuthService
Controllers/AuthController.cs
Models/ApplicationUser.cs
Models/RefreshToken.cs
DTOs/RegisterRequest.cs
DTOs/LoginRequest.cs
DTOs/AuthResponse.cs
Data/AuthDbContext.cs
Services/JwtTokenService.cs
Services/RefreshTokenService.cs
Program.cs
appsettings.json
ApiGateway
Program.cs
ocelot.json
appsettings.json
UserService
Controllers/UsersController.cs
Controllers/AdminController.cs
Data/UserDbContext.cs
Models/User.cs
ProductService
Controllers/ProductsController.cs
Data/ProductDbContext.cs
Models/Product.cs
OrderService
Controllers/OrdersController.cs
Data/OrderDbContext.cs
Models/Order.cs
ecommerce-ui
core/services/auth.service.ts
core/interceptors/auth.interceptor.ts
core/guards/auth.guard.ts
core/guards/role.guard.ts
pages/login/login.component.ts
pages/dashboard/dashboard.component.ts
app.config.ts
app.routes.ts
23. Complete Database Architecture
SQL Server
AuthDb
Identity database
AspNetUsers
AspNetRoles
AspNetUserRoles
RefreshTokens
UserDb
User profiles
- Users
ProductDb
Product management
- Products
OrderDb
Order management
- Orders
Each database is owned by its respective service. Do not create cross-service database foreign keys.
24. Production Security Improvements
Before deploying this architecture to production, address these additional requirements:
Requirement | Why it matters |
|---|---|
RSA/ECDSA JWT signing | Keep private signing key only in AuthService |
Refresh token reuse detection | Detect stolen or replayed refresh tokens |
Refresh token concurrency control | Prevent simultaneous rotation races |
CSRF protection | Protect cookie-based refresh/logout endpoints |
Email verification | Verify user identity |
Password reset | Secure forgotten-password workflow |
Rate limiting | Protect login and registration |
Account lockout | Prevent brute-force attempts |
HTTPS everywhere | Protect tokens in transit |
Service-to-service identity | Secure internal API communication |
Authorization ownership checks | Prevent customers accessing other customers' data |
One important distinction: JWT access tokens remain valid until expiration unless you add a revocation mechanism or use short lifetimes. Logging out revokes the refresh token, but does not automatically invalidate an already issued access token. Keep access tokens short-lived.
Also, add explicit collection routes such as /users, /products, and /orders to Ocelot, alongside the /{everything} routes, so list and create operations work correctly.
0 Comments
POST Answer of Questions and ASK to Doubt