Skip to content

Commit a731e26

Browse files
committed
Authentication
1 parent 6bc7144 commit a731e26

7 files changed

Lines changed: 99 additions & 27 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
namespace Common;
2+
3+
using System.Text.Json;
4+
using Microsoft.Azure.Functions.Worker;
5+
6+
public static class AuthHelper
7+
{
8+
public static bool TryGetTokenFromHeaders(FunctionContext context, out string token)
9+
{
10+
token = null!;
11+
12+
context.BindingContext.BindingData.TryGetValue("Headers", out var headersObj);
13+
14+
if(headersObj is not string headersStr)
15+
{
16+
return false;
17+
}
18+
var headers = JsonSerializer.Deserialize<Dictionary<string, string>>(headersStr);
19+
if(headers == null)
20+
{
21+
return false;
22+
}
23+
24+
if(!headers.TryGetValue("Authorization", out var authHeader) || !authHeader.StartsWith("Bearer "))
25+
{
26+
return false;
27+
}
28+
29+
token = authHeader.Substring("Bearer ".Length).Trim();
30+
return true;
31+
}
32+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
namespace Common;
2+
3+
using System.Net;
4+
using Microsoft.Azure.Functions.Worker;
5+
using Microsoft.Azure.Functions.Worker.Middleware;
6+
using Microsoft.Extensions.Logging;
7+
8+
public class CIS2AuthMiddleware : IFunctionsWorkerMiddleware
9+
{
10+
11+
private readonly ILogger<CIS2AuthMiddleware> _logger;
12+
private readonly ICreateResponse _createResponse;
13+
private readonly IAuthenticationService _authService;
14+
15+
public CIS2AuthMiddleware(ILogger<CIS2AuthMiddleware> logger, ICreateResponse createResponse, IAuthenticationService authService)
16+
{
17+
_logger = logger;
18+
_createResponse = createResponse;
19+
_authService = authService;
20+
}
21+
22+
public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
23+
{
24+
var req = await context.GetHttpRequestDataAsync();
25+
26+
var tokenExists = AuthHelper.TryGetTokenFromHeaders(context, out var token);
27+
28+
if(!tokenExists)
29+
{
30+
_logger.LogWarning("Authorization header is missing or invalid");
31+
var response = await _createResponse.CreateHttpResponseWithBodyAsync(HttpStatusCode.Unauthorized, req!, "Unauthorized: Missing or invalid Authorization header.");
32+
context.GetInvocationResult().Value = response;
33+
return;
34+
}
35+
36+
var validateToken = await _authService.ValidateTokenAsync(token);
37+
38+
if(!validateToken)
39+
{
40+
_logger.LogWarning("Token validation failed");
41+
var response = await _createResponse.CreateHttpResponseWithBodyAsync(HttpStatusCode.Unauthorized, req!, "Unauthorized: Invalid token.");
42+
context.GetInvocationResult().Value = response;
43+
return;
44+
}
45+
46+
context.Items["AuthToken"] = token;
47+
await next(context);
48+
}
49+
}

application/CohortManager/src/Functions/Shared/Common/Authentication/IAuthenticationService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@ namespace Common;
44

55
public interface IAuthenticationService
66
{
7-
Task<bool> ValidateAccess(HttpRequestData request);
7+
Task<bool> ValidateTokenAsync(string token);
88
}

application/CohortManager/src/Functions/Shared/Common/Authentication/JwtAuthentication.cs

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,8 @@ public JWTAuthentication(IOptions<AuthConfig> authConfig, ILogger<JWTAuthenticat
2626
);
2727
}
2828

29-
public async Task<bool> ValidateAccess(HttpRequestData request)
29+
public async Task<bool> ValidateTokenAsync(string token)
3030
{
31-
32-
var authHeader = request.Headers.Single(x => x.Key == "Authorization").Value.FirstOrDefault();
33-
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
34-
{
35-
_logger.LogWarning("Authorization header is missing or does not start with 'Bearer '");
36-
return false;
37-
}
38-
var token = authHeader.Substring("Bearer ".Length).Trim();
39-
4031
try
4132
{
4233
var oidcConfig = await _configurationManager.GetConfigurationAsync();
@@ -67,8 +58,6 @@ public async Task<bool> ValidateAccess(HttpRequestData request)
6758
_logger.LogError(ex, "An unexpected error occurred during token validation");
6859
return false;
6960
}
70-
// Implement JWT validation logic here using _authConfig.MetaDataUrl and _authConfig.ClientId
71-
// This is a placeholder implementation and should be replaced with actual JWT validation logic.
7261
}
7362

7463
}

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,14 @@ public static IHostBuilder AddAuthentication(this IHostBuilder hostBuilder)
99
{
1010

1111
hostBuilder.AddConfiguration<AuthConfig>();
12+
hostBuilder.ConfigureFunctionsWorkerDefaults(workerOptions =>
13+
{
14+
workerOptions.UseMiddleware<CIS2AuthMiddleware>();
15+
});
1216
hostBuilder.ConfigureServices((context, services) =>
1317
{
14-
services.AddSingleton<IAuthenticationService, JWTAuthentication>();
18+
19+
//services.AddSingleton<IAuthenticationService, JWTAuthentication>();
1520
});
1621
return hostBuilder;
1722
}

application/CohortManager/src/Functions/screeningDataServices/GetValidationExceptions/GetValidationExceptions.cs

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,13 @@ public class GetValidationExceptions
2424
private readonly IValidationExceptionData _validationData;
2525
private readonly IHttpParserHelper _httpParserHelper;
2626
private readonly IPaginationService<ValidationException> _paginationService;
27-
private readonly IAuthenticationService _authenticationService;
2827

29-
public GetValidationExceptions(ILogger<GetValidationExceptions> logger, ICreateResponse createResponse, IValidationExceptionData validationData, IHttpParserHelper httpParserHelper, IPaginationService<ValidationException> paginationService, IAuthenticationService authenticationService)
28+
public GetValidationExceptions(ILogger<GetValidationExceptions> logger, ICreateResponse createResponse, IValidationExceptionData validationData, IHttpParserHelper httpParserHelper, IPaginationService<ValidationException> paginationService)
3029
{
3130
_logger = logger;
3231
_createResponse = createResponse;
3332
_validationData = validationData;
3433
_httpParserHelper = httpParserHelper;
35-
_authenticationService = authenticationService;
3634
_paginationService = paginationService;
3735
}
3836

@@ -59,14 +57,6 @@ public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymou
5957
var isReport = _httpParserHelper.GetQueryParameterAsBool(req, "isReport");
6058
var ruleId = _httpParserHelper.GetQueryParameterAsNullableInt(req, "ruleId");
6159
var dateCreated = _httpParserHelper.GetQueryParameterAsDateTime(req, "dateCreated");
62-
63-
var validated = await _authenticationService.ValidateAccess(req);
64-
65-
if(!validated)
66-
{
67-
return _createResponse.CreateHttpResponse(HttpStatusCode.Unauthorized, req, "Unauthorized access.");
68-
}
69-
7060
try
7161
{
7262
if (exceptionId > 0)

application/CohortManager/src/Functions/screeningDataServices/GetValidationExceptions/Program.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,21 @@
1010

1111
var host = new HostBuilder()
1212
.AddConfiguration<GetValidationExceptionsConfig>(out GetValidationExceptionsConfig config)
13-
.ConfigureFunctionsWorkerDefaults()
13+
.AddConfiguration<AuthConfig>()
14+
.ConfigureFunctionsWorkerDefaults(
15+
workerOptions =>
16+
{
17+
workerOptions.UseMiddleware<CIS2AuthMiddleware>();
18+
}
19+
)
1420
.AddDataServicesHandler()
1521
.AddDataService<ExceptionManagement>(config.ExceptionManagementDataServiceURL)
1622
.AddDataService<ParticipantDemographic>(config.DemographicDataServiceURL)
1723
.Build()
18-
.AddAuthentication()
24+
//.AddAuthentication()
1925
.ConfigureServices(services =>
2026
{
27+
services.AddSingleton<IAuthenticationService, JWTAuthentication>();
2128
services.AddTransient<IValidationExceptionData, ValidationExceptionData>();
2229
services.AddSingleton<ICreateResponse, CreateResponse>();
2330
services.AddSingleton<IHttpParserHelper, HttpParserHelper>();

0 commit comments

Comments
 (0)