Skip to content

Commit

Permalink
Create NatsAuthOpts.TokenHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
gsutton authored and garrett-sutton committed Jan 14, 2025
1 parent b27eb7c commit 21c6654
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/NATS.Client.Core/Internal/UserCredentials.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public UserCredentials(NatsAuthOpts authOpts)
Seed = authOpts.Seed;
NKey = authOpts.NKey;
Token = authOpts.Token;
TokenHandler = authOpts.TokenHandler;

if (!string.IsNullOrEmpty(authOpts.CredsFile))
{
Expand All @@ -31,6 +32,8 @@ public UserCredentials(NatsAuthOpts authOpts)

public string? Token { get; }

public Func<ValueTask<string>>? TokenHandler { get; }

public string? Sign(string? nonce)
{
if (Seed == null || nonce == null)
Expand All @@ -43,11 +46,11 @@ public UserCredentials(NatsAuthOpts authOpts)
return sig;
}

internal void Authenticate(ClientOpts opts, ServerInfo? info)
internal async Task AuthenticateAsync(ClientOpts opts, ServerInfo? info)
{
opts.JWT = Jwt;
opts.NKey = NKey;
opts.AuthToken = Token;
opts.AuthToken = TokenHandler != null ? await TokenHandler().ConfigureAwait(false) : Token;
opts.Sig = info is { AuthRequired: true, Nonce: { } } ? Sign(info.Nonce) : null;
}

Expand Down
7 changes: 7 additions & 0 deletions src/NATS.Client.Core/NatsAuthOpts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ public record NatsAuthOpts

public string? Token { get; init; }

/// <summary>
/// A callback that returns a token string.
/// If this is set, it takes precedence over <see cref="Token"/>.
/// </summary>
public Func<ValueTask<string>>? TokenHandler { get; init; }

public string? Jwt { get; init; }

public string? NKey { get; init; }
Expand All @@ -23,6 +29,7 @@ public record NatsAuthOpts
public bool IsAnonymous => string.IsNullOrEmpty(Username)
&& string.IsNullOrEmpty(Password)
&& string.IsNullOrEmpty(Token)
&& TokenHandler == null
&& string.IsNullOrEmpty(Jwt)
&& string.IsNullOrEmpty(Seed)
&& string.IsNullOrEmpty(CredsFile)
Expand Down
5 changes: 4 additions & 1 deletion src/NATS.Client.Core/NatsConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,10 @@ private async ValueTask SetupReaderWriterAsync(bool reconnect)
infoParsedSignal.SetResult();

// Authentication
_userCredentials?.Authenticate(_clientOpts, WritableServerInfo);
if (_userCredentials != null)
{
await _userCredentials.AuthenticateAsync(_clientOpts, WritableServerInfo).ConfigureAwait(false);
}

await using (var priorityCommandWriter = new PriorityCommandWriter(this, _pool, _socket!, Opts, Counter, EnqueuePing))
{
Expand Down

0 comments on commit 21c6654

Please sign in to comment.