feat: add IAuthenticator interface and TokenAuthenticator with constant-time comparison

This commit is contained in:
Joseph Doherty
2026-02-22 22:24:53 -05:00
parent 0cce771907
commit 562f89744d
4 changed files with 113 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
using System.Security.Cryptography;
using System.Text;
namespace NATS.Server.Auth;
public sealed class TokenAuthenticator : IAuthenticator
{
private readonly byte[] _expectedToken;
public TokenAuthenticator(string token)
{
_expectedToken = Encoding.UTF8.GetBytes(token);
}
public AuthResult? Authenticate(ClientAuthContext context)
{
var clientToken = context.Opts.Token;
if (string.IsNullOrEmpty(clientToken))
return null;
var clientBytes = Encoding.UTF8.GetBytes(clientToken);
if (!CryptographicOperations.FixedTimeEquals(clientBytes, _expectedToken))
return null;
return new AuthResult { Identity = "token" };
}
}