using System.Text; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; namespace Bff.Tests; /// Mints JWTs for the BFF tests — signed with the factory's test key (valid) or otherwise /// (a wrong key / expired) to exercise the bearer validation the BFF configures. internal static class TestTokens { public static string Valid(string bsn) => Create(bsn, BffFactory.TestSigningKey, expired: false); public static string Expired(string bsn) => Create(bsn, BffFactory.TestSigningKey, expired: true); public static string WrongKey(string bsn) => Create( bsn, new SymmetricSecurityKey(Encoding.UTF8.GetBytes("a-different-signing-key-256-bits-long-indeed-yes!")), expired: false); /// A medewerker-realm token carrying the given realm roles under realm_access.roles /// (Keycloak's shape), signed with the valid test key. Used to exercise behandel authorization. public static string Medewerker(params string[] roles) { var handler = new JsonWebTokenHandler(); return handler.CreateToken(new SecurityTokenDescriptor { Claims = new Dictionary { ["realm_access"] = new Dictionary { ["roles"] = roles }, }, Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(BffFactory.TestSigningKey, SecurityAlgorithms.HmacSha256), }); } private static string Create(string bsn, SymmetricSecurityKey key, bool expired) { var handler = new JsonWebTokenHandler(); return handler.CreateToken(new SecurityTokenDescriptor { Claims = new Dictionary { ["bsn"] = bsn }, Expires = DateTime.UtcNow.AddMinutes(expired ? -5 : 30), SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256), }); } }