Skip to content

Commit 45c893b

Browse files
author
PalashKarmaker
committed
changes
1 parent 1461a90 commit 45c893b

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Core.Arango/Transport/ArangoHttpTransport.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public class ArangoHttpTransport(IArangoConfiguration configuration) : IArangoTr
1919
{
2020
private static readonly HttpClient DefaultHttpClient = new();
2121
string _auth = "";
22+
DateTime _authValidUntil = DateTime.MinValue;
2223
/// <inheritdoc />
2324
protected string Auth
2425
{
@@ -29,13 +30,35 @@ protected string Auth
2930
return _auth;
3031
}
3132
}
33+
private async Task Authenticate(bool auth, CancellationToken cancellationToken)
34+
{
35+
if (string.IsNullOrWhiteSpace(configuration.User))
36+
return;
3237

38+
if (auth && (_auth == null || _authValidUntil < DateTime.UtcNow))
39+
{
40+
var authResponse = await SendAsync<AuthResponse>(HttpMethod.Post,
41+
"/_open/auth",
42+
new AuthRequest
43+
{
44+
Username = configuration.User,
45+
Password = configuration.Password ?? string.Empty
46+
}, auth: false, cancellationToken: cancellationToken).ConfigureAwait(false);
47+
48+
var jwt = authResponse.Jwt;
49+
var token = new JwtSecurityToken(jwt.Replace("=", ""));
50+
_auth = $"Bearer {jwt}";
51+
_authValidUntil = token.ValidTo.AddMinutes(-5);
52+
}
53+
}
3354
/// <inheritdoc />
3455
public async Task<T> SendAsync<T>(HttpMethod m, string url, object body = null,
3556
string transaction = null, bool throwOnError = true, bool auth = true,
3657
IDictionary<string, string> headers = null,
3758
CancellationToken cancellationToken = default)
3859
{
60+
await Authenticate(auth, cancellationToken).ConfigureAwait(false);
61+
3962
using var req = new HttpRequestMessage(m, configuration.Server + url);
4063
ApplyHeaders(transaction, auth, req, headers);
4164

0 commit comments

Comments
 (0)