Yes. A typical implementation in ASP.NET Core issues JWTs from a login endpoint and validates them in the API. (For larger systems, an identity provider such as Entra ID, Keycloak or Auth0 often issues the tokens instead.) What is needed to create a JWT 1. Claims about the user: sub (user ID), name or email, roles or permissions, and a unique jti. 2. Issuer (iss): who created the token, e.g. https://auth.myapp.com. 3. Audience (aud): which API the token is for. 4. Lifetime: issued-at (iat), not-before (nbf) and expiry (exp). 5. A signing key and algorithm: a strong symmetric secret (at least 256 bits) with HS256, or an RSA or ECDSA private key with RS256 or ES256. Keys must come from a secure store such as Key Vault, never source code. Creating the token: var claims = new List<Claim> { new(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new(JwtRegisteredClaimNames.Email, user.Email), new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; claims.AddRange(user.Roles.Select(r => new Claim(ClaimTypes.Role, r))); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]!)); var descriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Issuer = config["Jwt:Issuer"], Audience = config["Jwt:Audience"], Expires = DateTime.UtcNow.AddMinutes(15), SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256) }; string token = new JsonWebTokenHandler().CreateToken(descriptor); Validating it in the API: builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(o => o.TokenValidationParameters = new() { ValidateIssuer = true, ValidIssuer = config["Jwt:Issuer"], ValidateAudience = true, ValidAudience = config["Jwt:Audience"], ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(1), ValidateIssuerSigningKey = true, IssuerSigningKey = key }); app.UseAuthentication(); app.UseAuthorization(); Then protect endpoints with [Authorize] or policies. Also mention: short-lived access tokens plus refresh tokens stored and rotated server-side, password hashing (ASP.NET Core Identity's PasswordHasher), HTTPS everywhere, and never putting secrets or sensitive personal data in the payload because it is readable by anyone.
Ravindra Wadile · · 0 likes