Files
RecRoomPhotonAuthentication…/RecRoomPhotonAuthenticationServer/JWTValidator.cs
2026-08-19 16:33:01 -04:00

60 lines
1.6 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace RecRoomPhotonAuthenticationServer;
public class JWTValidator
{
private readonly RsaSecurityKey _securityKey;
public JWTValidator()
{
var rsa = RSA.Create();
var pem = File.ReadAllText(App.rsaPath);
rsa.ImportFromPem(pem);
_securityKey = new RsaSecurityKey(rsa)
{
KeyId = App.keyId
};
}
public string? ValidateAndGetAccountId(string token)
{
try
{
var handler = new JwtSecurityTokenHandler();
handler.InboundClaimTypeMap.Clear();
// you probably have to change these
var parameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = _securityKey,
ValidateIssuer = true,
ValidIssuer = "https://auth.lapis.codes",
ValidateAudience = true,
ValidAudiences =
[
"https://api.lapis.codes/resources",
"https://auth.lapis.codes/resources"
],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
var principal = handler.ValidateToken(token, parameters, out SecurityToken validatedToken);
var accountIdClaim = principal.Claims.FirstOrDefault(c => c.Type == "sub");
return accountIdClaim?.Value;
}
catch (Exception ex)
{
return null;
}
}
}