Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed APIKey fallback #622

Merged
merged 5 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 0 additions & 45 deletions Dfe.Academies.Api.Infrastructure/Security/ApiKeyOrRoleHandler.cs

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,37 @@ public static class AuthorizationExtensions
{
public static IServiceCollection AddCustomAuthorization(this IServiceCollection services, IConfiguration configuration)
{
// Add both Azure AD (JWT) and API Key authentication mechanisms
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddMicrosoftIdentityWebApi(configuration.GetSection("AzureAd"));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(configuration.GetSection("AzureAd"));

services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();

var roles = configuration.GetSection("Authorization:Roles").Get<string[]>();
if (roles != null)
{
foreach (var role in roles)
{
options.AddPolicy(role, policy =>
{
policy.Requirements.Add(new ApiKeyOrRoleRequirement(role));
});
options.AddPolicy(role, policy => policy.RequireRole(role));
}
}

// Add claim-based policies
var claims = configuration.GetSection("Authorization:Claims").Get<Dictionary<string, string>>();

if (claims == null) return;

foreach (var claim in claims)
if (claims != null)
{
options.AddPolicy($"{claim.Key}", policy =>
policy.RequireClaim(claim.Key, claim.Value));
foreach (var claim in claims)
{
options.AddPolicy($"{claim.Key}", policy =>
policy.RequireClaim(claim.Key, claim.Value));
}
}
});

services.AddSingleton<IAuthorizationHandler, ApiKeyOrRoleHandler>();

return services;
}
}

}
26 changes: 11 additions & 15 deletions Dfe.PersonsApi.Client/Security/TokenAcquisitionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,25 @@ namespace Dfe.PersonsApi.Client.Security
public class TokenAcquisitionService : ITokenAcquisitionService
{
private readonly PersonsApiClientSettings _settings;
private readonly IConfidentialClientApplication _app;
private AuthenticationResult? _authResult;
private readonly Lazy<IConfidentialClientApplication> _app;

public TokenAcquisitionService(PersonsApiClientSettings settings)
{
_settings = settings;
_settings = settings ?? throw new ArgumentNullException(nameof(settings));

_app = ConfidentialClientApplicationBuilder.Create(_settings.ClientId)
.WithClientSecret(_settings.ClientSecret)
.WithAuthority(new Uri(_settings.Authority!))
.Build();
_app = new Lazy<IConfidentialClientApplication>(() =>
ConfidentialClientApplicationBuilder.Create(_settings.ClientId)
.WithClientSecret(_settings.ClientSecret)
.WithAuthority(new Uri(_settings.Authority!))
.Build());
}

public async Task<string> GetTokenAsync()
{
// Check if the current token is about to expire
if (_authResult == null || _authResult.ExpiresOn <= DateTimeOffset.UtcNow.AddMinutes(-1))
{
_authResult = await _app.AcquireTokenForClient(new[] { _settings.Scope })
.ExecuteAsync();
}
var authResult = await _app.Value.AcquireTokenForClient(new[] { _settings.Scope })
.ExecuteAsync();

return _authResult.AccessToken;
return authResult.AccessToken;
}
}
}
}
6 changes: 0 additions & 6 deletions PersonsApi/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,6 @@
}
},
"AllowedHosts": "*",
"ApiKeys": [
{
"UserName": "Demo User",
"ApiKey": "app-key"
}
],
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=sip;User ID=sa;Password=StrongPassword905;TrustServerCertificate=True"
},
Expand Down
6 changes: 0 additions & 6 deletions PersonsApi/appsettings.Test.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,6 @@
}
},
"AllowedHosts": "*",
"ApiKeys": [
{
"UserName": "Demo User",
"ApiKey": "app-key"
}
],
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "platform.education.gov.uk",
Expand Down
6 changes: 0 additions & 6 deletions PersonsApi/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@
"ConnectionString": "Copy connection string from Application Insights Resource Overview"
},
"AllowedHosts": "*",
"ApiKeys": [
{
"UserName": "Demo User",
"ApiKey": "app-key"
}
],
"SyncAcademyConversionProjectsSchedule": "0 0/15 * * * *",
"Serilog": {
"Using": [
Expand Down
Loading