100 lines
3.3 KiB
C#
100 lines
3.3 KiB
C#
using Azure.Core;
|
|
using Azure.Identity;
|
|
using Core.Cerberos.Adapters.Common.Constants;
|
|
using MongoDB.Driver.Authentication.Oidc;
|
|
|
|
namespace Core.Cerberos.Provider.Providers
|
|
{
|
|
public class HeathOidcCallback : IOidcCallback
|
|
{
|
|
private readonly string _audience;
|
|
private readonly string _environment;
|
|
public HeathOidcCallback(string audience)
|
|
{
|
|
_audience = audience;
|
|
_environment = Environment.GetEnvironmentVariable(EnvironmentVariables.Stage) ?? string.Empty;
|
|
}
|
|
|
|
public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
AccessToken token;
|
|
|
|
TokenRequestContext tokenRequestContext =
|
|
new TokenRequestContext(
|
|
new[] { _audience }
|
|
);
|
|
|
|
if (_environment == "Local")
|
|
{
|
|
token =
|
|
new ChainedTokenCredential(
|
|
new ManagedIdentityCredential(),
|
|
new VisualStudioCredential(),
|
|
new VisualStudioCodeCredential(),
|
|
new SharedTokenCacheCredential()
|
|
)
|
|
.GetToken(
|
|
tokenRequestContext
|
|
);
|
|
}
|
|
else
|
|
{
|
|
token =
|
|
new ManagedIdentityCredential()
|
|
.GetToken(
|
|
tokenRequestContext
|
|
);
|
|
}
|
|
|
|
return new(token.Token, expiresIn: null);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
throw new Exception($"An error ocurred while trying to get the OIDC token to connect to the database, ERROR: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
TokenRequestContext tokenRequestContext =
|
|
new TokenRequestContext(
|
|
new[] { _audience }
|
|
);
|
|
|
|
AccessToken token;
|
|
|
|
if (_environment == "Local")
|
|
{
|
|
token = await new ChainedTokenCredential(
|
|
new ManagedIdentityCredential(),
|
|
new VisualStudioCredential(),
|
|
new VisualStudioCodeCredential(),
|
|
new SharedTokenCacheCredential()
|
|
)
|
|
.GetTokenAsync(
|
|
tokenRequestContext, cancellationToken
|
|
).ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
token = await new ManagedIdentityCredential()
|
|
.GetTokenAsync(
|
|
tokenRequestContext, cancellationToken
|
|
).ConfigureAwait(false);
|
|
}
|
|
|
|
return new(token.Token, expiresIn: null);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new Exception($"An error ocurred while trying to get the OIDC token to connect to the database, ERROR: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
}
|