2022-02-23 09:32:19 -08:00
|
|
|
using System.Net.Http.Headers;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using k8s.KubeConfigModels;
|
2022-02-25 13:33:23 -08:00
|
|
|
using k8s.Autorest;
|
2022-02-23 09:32:19 -08:00
|
|
|
|
|
|
|
|
namespace k8s.Authentication
|
|
|
|
|
{
|
|
|
|
|
public class ExecTokenProvider : ITokenProvider
|
|
|
|
|
{
|
|
|
|
|
private readonly ExternalExecution exec;
|
|
|
|
|
private ExecCredentialResponse response;
|
|
|
|
|
|
|
|
|
|
public ExecTokenProvider(ExternalExecution exec)
|
|
|
|
|
{
|
|
|
|
|
this.exec = exec;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool NeedsRefresh()
|
|
|
|
|
{
|
|
|
|
|
if (response?.Status == null)
|
|
|
|
|
{
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-03 10:46:21 -07:00
|
|
|
if (response.Status.ExpirationTimestamp == null)
|
2022-02-23 09:32:19 -08:00
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-03 10:46:21 -07:00
|
|
|
return DateTime.UtcNow.AddSeconds(30) > response.Status.ExpirationTimestamp;
|
2022-02-23 09:32:19 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
if (NeedsRefresh())
|
|
|
|
|
{
|
|
|
|
|
await RefreshToken().ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return new AuthenticationHeaderValue("Bearer", response.Status.Token);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task RefreshToken()
|
|
|
|
|
{
|
|
|
|
|
response =
|
|
|
|
|
await Task.Run(() => KubernetesClientConfiguration.ExecuteExternalCommand(this.exec)).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|