Fetch keyvault variables only if they are not set as environment variables (#361)

This commit is contained in:
sushilraje 2019-07-16 11:17:37 -07:00 коммит произвёл GitHub
Родитель 577246a20d
Коммит 120f51fad5
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
6 изменённых файлов: 42 добавлений и 7 удалений

Просмотреть файл

@ -53,6 +53,7 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
private TokenValidationParameters tokenValidationParams; private TokenValidationParameters tokenValidationParams;
private readonly bool authRequired; private readonly bool authRequired;
private bool tokenValidationInitialized; private bool tokenValidationInitialized;
private DateTime tokenValidationExpiration;
public AuthMiddleware( public AuthMiddleware(
// ReSharper disable once UnusedParameter.Local // ReSharper disable once UnusedParameter.Local
@ -67,6 +68,7 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
this.log = log; this.log = log;
this.authRequired = config.AuthRequired; this.authRequired = config.AuthRequired;
this.tokenValidationInitialized = false; this.tokenValidationInitialized = false;
this.tokenValidationExpiration = DateTime.UtcNow;
// This will show in development mode, or in case auth is turned off // This will show in development mode, or in case auth is turned off
if (!this.authRequired) if (!this.authRequired)
@ -83,7 +85,8 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
this.config.JwtIssuer, this.config.JwtIssuer,
this.config.JwtAudience, this.config.JwtAudience,
this.config.JwtAllowedAlgos, this.config.JwtAllowedAlgos,
this.config.JwtClockSkew this.config.JwtClockSkew,
this.config.OpenIdTimeToLive
}); });
this.InitializeTokenValidationAsync(CancellationToken.None).Wait(); this.InitializeTokenValidationAsync(CancellationToken.None).Wait();
@ -196,7 +199,8 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
private async Task<bool> InitializeTokenValidationAsync(CancellationToken token) private async Task<bool> InitializeTokenValidationAsync(CancellationToken token)
{ {
if (this.tokenValidationInitialized) return true; // If the token has been initialized and is not past expiry, return.
if (this.tokenValidationInitialized && !this.TokenValidationExpired()) return true;
try try
{ {
@ -224,6 +228,7 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
}; };
this.tokenValidationInitialized = true; this.tokenValidationInitialized = true;
this.tokenValidationExpiration = DateTime.UtcNow.Add(this.config.OpenIdTimeToLive);
} }
catch (Exception e) catch (Exception e)
{ {
@ -232,5 +237,14 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
return this.tokenValidationInitialized; return this.tokenValidationInitialized;
} }
/// <summary>
/// Checks if the OpenId Connect token has hit the expiration time.
/// </summary>
/// <returns>true if the token has expired</returns>
private bool TokenValidationExpired()
{
return this.tokenValidationExpiration > DateTime.UtcNow;
}
} }
} }

Просмотреть файл

@ -36,6 +36,12 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
// Clock skew allowed when validating tokens expiration // Clock skew allowed when validating tokens expiration
// Default: 2 minutes // Default: 2 minutes
TimeSpan JwtClockSkew { get; set; } TimeSpan JwtClockSkew { get; set; }
// Time to live for the OpenId Connect validation token.
// The metadata settings will expire so the token needs to be
// periodically recreated.
// Default: 7 days
TimeSpan OpenIdTimeToLive { get; set; }
} }
public class ClientAuthConfig : IClientAuthConfig public class ClientAuthConfig : IClientAuthConfig
@ -49,5 +55,6 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Auth
public string JwtIssuer { get; set; } public string JwtIssuer { get; set; }
public string JwtAudience { get; set; } public string JwtAudience { get; set; }
public TimeSpan JwtClockSkew { get; set; } public TimeSpan JwtClockSkew { get; set; }
public TimeSpan OpenIdTimeToLive { get; set; }
} }
} }

Просмотреть файл

@ -92,6 +92,9 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Runtime
private const string JWT_AUDIENCE_KEY = JWT_KEY + "audience"; private const string JWT_AUDIENCE_KEY = JWT_KEY + "audience";
private const string JWT_CLOCK_SKEW_KEY = JWT_KEY + "clock_skew_seconds"; private const string JWT_CLOCK_SKEW_KEY = JWT_KEY + "clock_skew_seconds";
private const string OPEN_ID_KEY = APPLICATION_KEY + "ClientAuth:OpenIdConnect:";
private const string OPEN_ID_TTL_KEY = OPEN_ID_KEY + "timeToLiveDays";
private const string DEPLOYMENT_KEY = APPLICATION_KEY + "Deployment:"; private const string DEPLOYMENT_KEY = APPLICATION_KEY + "Deployment:";
private const string AZURE_SUBSCRIPTION_DOMAIN = DEPLOYMENT_KEY + "azure_subscription_domain"; private const string AZURE_SUBSCRIPTION_DOMAIN = DEPLOYMENT_KEY + "azure_subscription_domain";
private const string AZURE_SUBSCRIPTION_ID = DEPLOYMENT_KEY + "azure_subscription_id"; private const string AZURE_SUBSCRIPTION_ID = DEPLOYMENT_KEY + "azure_subscription_id";
@ -161,6 +164,8 @@ namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.Runtime
JwtAudience = configData.GetString(JWT_AUDIENCE_KEY, String.Empty), JwtAudience = configData.GetString(JWT_AUDIENCE_KEY, String.Empty),
// By default the allowed clock skew is 2 minutes // By default the allowed clock skew is 2 minutes
JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)), JwtClockSkew = TimeSpan.FromSeconds(configData.GetInt(JWT_CLOCK_SKEW_KEY, 120)),
// By default the time to live for the OpenId connect token is 7 days
OpenIdTimeToLive = TimeSpan.FromDays(configData.GetInt(OPEN_ID_TTL_KEY, 7))
}; };
} }

Просмотреть файл

@ -36,7 +36,7 @@
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.1" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.1" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="2.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="2.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="2.1.5" /> <PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="5.4.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Services\Services.csproj" /> <ProjectReference Include="..\Services\Services.csproj" />

Просмотреть файл

@ -208,6 +208,11 @@ audience="${?PCS_AUTH_AUDIENCE}"
# Default: 2 minutes # Default: 2 minutes
clock_skew_seconds = 300 clock_skew_seconds = 300
[TelemetryService:ClientAuth:OpenIdConnect]
; Time to live for the OpenId Connect validation token.
; The metadata settings will expire so the token needs to be periodically recreated.
; Default: 7 days
timeToLiveDays = 7
# For more information about ASP.NET logging see # For more information about ASP.NET logging see
# https://docs.microsoft.com/aspnet/core/fundamentals/logging # https://docs.microsoft.com/aspnet/core/fundamentals/logging

Просмотреть файл

@ -81,10 +81,14 @@ set_env_vars() {
while test ${#} -gt 0 while test ${#} -gt 0
do do
_key=$1 _key=$1
_value=$(_get_keyvault_secret $2)
if [ -z "${!_key}" ]; then
# export in current shell _value=$(_get_keyvault_secret $2)
export $_key=$_value # export in current shell
export $_key=$_value
else
echo "Variable $_key already set."
fi
shift shift
shift shift