Skip to content

Commit 7d93389

Browse files
chore: trying to get PDS changes to work in azure
1 parent da49f16 commit 7d93389

4 files changed

Lines changed: 51 additions & 30 deletions

File tree

application/CohortManager/src/Functions/DemographicServices/RetrievePDSDemographic/RetrievePDSDemographic.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymou
5050
{
5151
var nhsNumber = req.Query["nhsNumber"];
5252

53+
5354
var bearerToken = await _bearerTokenService.GetBearerToken();
5455
if (bearerToken == null)
5556
{

application/CohortManager/src/Functions/Shared/Common/AuthorizationClientCredentials.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,15 @@ public class AuthorizationClientCredentials : IAuthorizationClientCredentials
1212
private readonly IJwtTokenService _jwtHandler;
1313
private readonly JwtTokenServiceConfig _JwtTokenServiceConfig;
1414

15-
public AuthorizationClientCredentials(IJwtTokenService jwtTokenService, HttpClient httpClient, IOptions<JwtTokenServiceConfig> JwtTokenServiceConfig)
15+
private readonly ILogger<AuthorizationClientCredentials> _logger;
16+
17+
public AuthorizationClientCredentials(IJwtTokenService jwtTokenService, HttpClient httpClient, IOptions<JwtTokenServiceConfig> JwtTokenServiceConfig, ILogger<AuthorizationClientCredentials> logger)
1618
{
1719
_httpClient = httpClient;
1820
_jwtHandler = jwtTokenService;
1921

2022
_JwtTokenServiceConfig = JwtTokenServiceConfig.Value;
23+
_logger = logger;
2124
}
2225

2326
public async Task<string?> AccessToken(int expInMinutes = 1)
@@ -33,15 +36,15 @@ public AuthorizationClientCredentials(IJwtTokenService jwtTokenService, HttpClie
3336
var content = new FormUrlEncodedContent(values);
3437

3538
var response = await _httpClient.PostAsync(_JwtTokenServiceConfig.AuthTokenURL, content);
39+
var resBody = await response.Content.ReadAsStringAsync();
3640

3741
if (response.StatusCode != HttpStatusCode.OK)
3842
{
43+
_logger.LogError("there was an error getting the bearer token from the NHS token service. Response: {resBody}", resBody);
3944
return null;
4045
}
4146

42-
var resBody = await response.Content.ReadAsStringAsync();
4347
var parsed = JsonNode.Parse(resBody);
44-
4548
return parsed?["access_token"]?.ToString();
4649
}
4750
}

application/CohortManager/src/Functions/Shared/Common/BearerTokenService.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,14 @@ public BearerTokenService(
2323
}
2424
public async Task<string> GetBearerToken()
2525
{
26+
2627
if (_memoryCache.TryGetValue(AccessTokenCacheKey, out string? bearerToken))
2728
{
29+
_logger.LogInformation("bearer token found in memory cache");
2830
return bearerToken!;
2931
}
3032

31-
_logger.LogInformation("Refreshing bearer token...");
33+
_logger.LogInformation("Token not found in memory cache refreshing bearer token...");
3234
bearerToken = await _authClientCredentials.AccessToken();
3335

3436
if (bearerToken == null)

application/CohortManager/src/Functions/Shared/Common/Extensions/JwtTokenExtension.cs

Lines changed: 41 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ namespace Common;
77
using Azure.Security.KeyVault.Secrets;
88
using Microsoft.Extensions.DependencyInjection;
99
using Microsoft.Extensions.Hosting;
10+
using Microsoft.Extensions.Logging;
1011

1112
public static class JwtTokenExtension
1213
{
14+
1315
/// <summary>
1416
/// gets the private key from the local dir or from keyvault if the function is running in azure
1517
/// </summary>
@@ -18,40 +20,53 @@ public static class JwtTokenExtension
1820
/// <returns></returns>
1921
public static IHostBuilder AddJwtTokenSigning(this IHostBuilder hostBuilder, bool useFakeBearerTokenService = false)
2022
{
21-
JwtPrivateKey jwtPrivateKey;
22-
// Azure
23-
hostBuilder.AddConfiguration<JwtTokenServiceConfig>(out JwtTokenServiceConfig config);
24-
if (!string.IsNullOrEmpty(config.KeyVaultConnectionString))
25-
{
26-
var certClient = new CertificateClient(vaultUri: new Uri(config.KeyVaultConnectionString), credential: new DefaultAzureCredential());
27-
var privateKey = certClient.DownloadCertificate(config.KeyNamePrivateKey);
28-
29-
jwtPrivateKey = new JwtPrivateKey(CertificateToString(privateKey));
30-
}
31-
// Local
32-
else
33-
{
34-
jwtPrivateKey = new JwtPrivateKey(GetPrivateKey(config.LocalPrivateKeyFileName));
35-
}
23+
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
24+
var logger = loggerFactory.CreateLogger("program.cs");
3625

37-
var host = hostBuilder.ConfigureServices(_ =>
26+
JwtPrivateKey jwtPrivateKey;
27+
try
3828
{
39-
_.AddMemoryCache();
40-
_.AddSingleton(jwtPrivateKey);
41-
_.AddSingleton<IAuthorizationClientCredentials, AuthorizationClientCredentials>();
42-
_.AddSingleton<IJwtTokenService, JwtTokenService>();
43-
_.AddSingleton<ISigningCredentialsProvider, SigningCredentialsProvider>();
44-
if (!useFakeBearerTokenService)
29+
// Azure
30+
hostBuilder.AddConfiguration<JwtTokenServiceConfig>(out JwtTokenServiceConfig config);
31+
if (!string.IsNullOrEmpty(config.KeyVaultConnectionString))
4532
{
46-
_.AddSingleton<IBearerTokenService, BearerTokenService>();
33+
var certClient = new CertificateClient(vaultUri: new Uri(config.KeyVaultConnectionString), credential: new DefaultAzureCredential());
34+
var privateKey = certClient.DownloadCertificate(config.KeyNamePrivateKey);
35+
36+
logger.LogInformation("got certificate from key vault");
37+
jwtPrivateKey = new JwtPrivateKey(CertificateToString(privateKey.Value));
4738
}
39+
// Local
4840
else
4941
{
50-
_.AddSingleton<IBearerTokenService, BearerTokenServiceMock>();
42+
jwtPrivateKey = new JwtPrivateKey(GetPrivateKey(config.LocalPrivateKeyFileName));
5143
}
52-
});
5344

54-
return host;
45+
var host = hostBuilder.ConfigureServices(_ =>
46+
{
47+
_.AddMemoryCache();
48+
_.AddSingleton(jwtPrivateKey);
49+
_.AddSingleton<IAuthorizationClientCredentials, AuthorizationClientCredentials>();
50+
_.AddSingleton<IJwtTokenService, JwtTokenService>();
51+
_.AddSingleton<ISigningCredentialsProvider, SigningCredentialsProvider>();
52+
if (!useFakeBearerTokenService)
53+
{
54+
_.AddSingleton<IBearerTokenService, BearerTokenService>();
55+
}
56+
else
57+
{
58+
_.AddSingleton<IBearerTokenService, BearerTokenServiceMock>();
59+
}
60+
});
61+
62+
return host;
63+
}
64+
catch (Exception ex)
65+
{
66+
logger.LogError(ex, ex.Message);
67+
throw;
68+
}
69+
5570
}
5671

5772
private static string CertificateToString(X509Certificate2 certificate)

0 commit comments

Comments
 (0)