1. Where Should the JWT Token Be Generated?
What is it?
The JWT should be generated by a trusted backend authentication system, such as the ASP.NET Core Web API itself or a dedicated Identity Provider.
For a simple Angular + ASP.NET Core application:
Generate the JWT in ASP.NET Core after successfully validating the user's credentials.
Do not generate the JWT in Angular.
Flow
Angular
│
│ Username + Password
▼
ASP.NET Core Web API
│
├── Validate user credentials
│
├── Create claims
│
├── Generate JWT
│
▼
Angular receives JWT
Simple Code
For a small application, this can be in an authentication service:
public string GenerateToken(string username)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Admin")
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!)
);
var credentials = new SigningCredentials(
key,
SecurityAlgorithms.HmacSha256
);
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler()
.WriteToken(token);
}
The controller can call it after credential validation:
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
// Normally validate against database
if (request.Username != "admin" ||
request.Password != "admin123")
{
return Unauthorized();
}
var token = _tokenService.GenerateToken(request.Username);
return Ok(new
{
token
});
}
In a Larger Application
Prefer separating responsibilities:
AuthController
│
▼
Authentication Service
│
├── Validate credentials
│
▼
Token Service
│
└── Generate JWT
For enterprise systems using OAuth 2.0/OpenID Connect, a dedicated Identity Provider/authorization server may issue the token instead:
Angular
│
▼
Identity Provider
│
└── Generates access token
│
▼
Angular
│
▼
ASP.NET Core API
2. Where Should the JWT Token Be Validated?
What is it?
The JWT must be validated by the backend API that protects the requested resource.
For Angular + ASP.NET Core:
ASP.NET Core Web API must validate the JWT before allowing access to protected endpoints.
Angular may read token information for UI purposes, but Angular must not be trusted to perform security validation.
Full Simple Validation Configuration
Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var key = builder.Configuration["Jwt:Key"]!;
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer =
builder.Configuration["Jwt:Issuer"],
ValidAudience =
builder.Configuration["Jwt:Audience"],
IssuerSigningKey =
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(key))
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Protected controller:
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new[]
{
"Laptop",
"Mobile",
"Keyboard"
});
}
}
How Validation Works
Angular sends:
GET /api/products
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
ASP.NET Core's JWT bearer authentication handler reads the token and validates it according to the configured parameters.
Angular
│
│ Authorization: Bearer <JWT>
▼
ASP.NET Core Web API
│
▼
JWT Bearer Authentication
│
├── Validate signature
├── Validate issuer
├── Validate audience
├── Validate expiration
│
▼
Create authenticated ClaimsPrincipal
│
▼
Authorization
│
▼
[Authorize]
│
▼
Controller Action
If the token is valid:
Valid JWT
↓
Authentication succeeds
↓
[Authorize] succeeds
↓
Controller executes
↓
200 OK
If the token is missing, expired, or invalid:
Invalid / Missing JWT
↓
Authentication fails
↓
[Authorize] blocks request
↓
401 Unauthorized
If authentication succeeds but the user lacks required permission:
Valid JWT
↓
Authenticated
↓
Required role/policy missing
↓
403 Forbidden
Should Angular Validate the JWT?
Angular can inspect the token for UI-related purposes.
For example:
if (isTokenExpired()) {
// redirect user to login
}
or:
if (userRole === 'Admin') {
// display Admin menu
}
But this is not security enforcement.
A malicious user controls their browser and can bypass Angular code entirely:
Attacker
│
│ Direct HTTP request
▼
ASP.NET Core API
Therefore the API must independently validate and authorize every protected request.
Key Points
| Responsibility | Where? |
|---|---|
| Enter username/password | Angular |
| Send login request | Angular |
| Validate credentials | ASP.NET Core / Identity Provider |
| Generate JWT | ASP.NET Core / Identity Provider |
| Receive JWT | Angular |
| Attach JWT to API request | Angular interceptor |
| Validate JWT | ASP.NET Core Web API |
Check [Authorize] |
ASP.NET Core |
| Check roles/policies | ASP.NET Core |
| Display/hide UI based on claims | Angular |
| Actual security enforcement | ASP.NET Core |
Golden Rule
JWT Generation
↓
Trusted Backend / Identity Provider
JWT Validation
↓
API receiving the protected request
Never trust Angular for authentication or authorization enforcement.
Interview Questions & Answers
1. Where should a JWT be generated?
A JWT should be generated by a trusted backend authentication service or Identity Provider after the user's credentials or authorization grant has been successfully validated.
2. Should Angular generate the JWT?
No. Angular runs in the user's browser and cannot safely hold the server's signing secret/private key. The JWT should be issued by a trusted server-side system.
3. Where should the JWT be validated?
The JWT should be validated by the ASP.NET Core Web API receiving the protected request.
4. What does ASP.NET Core validate?
Typically:
Signature
Issuer
Audience
Expiration
and then authorization checks roles, claims, or policies as required.
5. Can Angular validate the token?
Angular can inspect the token for UI behavior, such as checking expiration or showing menus. However, it must not be relied upon for security enforcement.
6. Who validates JWT in ASP.NET Core?
The JWT Bearer authentication handler configured with:
.AddJwtBearer(...)
validates the token and establishes the authenticated user (HttpContext.User).
7. What is the role of [Authorize]?
[Authorize] requires the request to satisfy the endpoint's authorization requirements.
[Authorize]
requires an authenticated user by default, while:
[Authorize(Roles = "Admin")]
also requires the appropriate role.
Interview Quick Answer
JWT should be generated by a trusted backend or Identity Provider after successful authentication. Angular receives the token and sends it with API requests. The ASP.NET Core Web API validates the token's signature, issuer, audience, and lifetime and then applies
[Authorize], roles, claims, or policies to determine access.