Skip to content

Commit dffc59e

Browse files
committed
Improve OidcTokenProvider error handling and expiry setting
The constructor `OidcTokenProvider` now always sets the `_expiry` field by calling `GetExpiryFromToken()`, regardless of whether `_idToken` is null or empty, removing the previous check for a non-empty `_idToken`. The `GetExpiryFromToken` method has been updated to handle invalid JWT token formats more gracefully. Instead of throwing an `ArgumentException` when the token format is invalid or when the 'exp' claim is missing, the method now returns a default value. The logic for parsing the JWT token and extracting the 'exp' claim has been wrapped in a try-catch block. If any exception occurs during this process, it is caught, and the method returns a default value instead of throwing an exception.
1 parent fe7863f commit dffc59e

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

src/KubernetesClient/Authentication/OidcTokenProvider.cs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,7 @@ public OidcTokenProvider(string clientId, string clientSecret, string idpIssuerU
2222
_idpIssuerUrl = idpIssuerUrl;
2323
_idToken = idToken;
2424
_refreshToken = refreshToken;
25-
26-
if (!string.IsNullOrEmpty(_idToken))
27-
{
28-
_expiry = GetExpiryFromToken();
29-
}
25+
_expiry = GetExpiryFromToken();
3026
}
3127

3228
public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken)
@@ -44,24 +40,28 @@ private DateTimeOffset GetExpiryFromToken()
4440
var parts = _idToken.Split('.');
4541
if (parts.Length != 3)
4642
{
47-
throw new ArgumentException("Invalid JWT token format.");
43+
return default;
4844
}
4945

50-
var payload = parts[1];
51-
var jsonBytes = Base64UrlDecode(payload);
52-
var json = Encoding.UTF8.GetString(jsonBytes);
53-
54-
using var document = JsonDocument.Parse(json);
55-
if (document.RootElement.TryGetProperty("exp", out var expElement))
46+
try
5647
{
57-
var exp = expElement.GetInt64();
58-
var expiryDateTime = DateTimeOffset.FromUnixTimeSeconds(exp);
59-
return expiryDateTime;
48+
var payload = parts[1];
49+
var jsonBytes = Base64UrlDecode(payload);
50+
var json = Encoding.UTF8.GetString(jsonBytes);
51+
52+
using var document = JsonDocument.Parse(json);
53+
if (document.RootElement.TryGetProperty("exp", out var expElement))
54+
{
55+
var exp = expElement.GetInt64();
56+
return DateTimeOffset.FromUnixTimeSeconds(exp);
57+
}
6058
}
61-
else
59+
catch
6260
{
63-
throw new ArgumentException("JWT token does not contain 'exp' claim.");
61+
// ignore to default
6462
}
63+
64+
return default;
6565
}
6666

6767
private static byte[] Base64UrlDecode(string input)

0 commit comments

Comments
 (0)