Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c3667a1
commit 53da8e3
Showing
3 changed files
with
148 additions
and
120 deletions.
There are no files selected for viewing
128 changes: 67 additions & 61 deletions
128
src/HappyCode.NetCoreBoilerplate.Api/Infrastructure/Filters/ApiKeyAuthorizationFilter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,61 +1,67 @@ | ||
using System.Linq; | ||
using System.Text.RegularExpressions; | ||
using HappyCode.NetCoreBoilerplate.Api.Infrastructure.Configurations; | ||
using HappyCode.NetCoreBoilerplate.Core; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.AspNetCore.Mvc.Filters; | ||
using Microsoft.Extensions.Options; | ||
using Microsoft.FeatureManagement; | ||
|
||
namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters | ||
{ | ||
public class ApiKeyAuthorizationFilter : IAsyncAuthorizationFilter | ||
{ | ||
private static readonly Regex _apiKeyRegex = new Regex(@"^[Aa][Pp][Ii][Kk][Ee][Yy]\s+(?<ApiKey>.+)$", RegexOptions.Compiled); | ||
|
||
private readonly IOptions<ApiKeySettings> _options; | ||
private readonly IFeatureManager _featureManager; | ||
|
||
public ApiKeyAuthorizationFilter(IOptions<ApiKeySettings> options, IFeatureManager featureManager) | ||
{ | ||
_options = options; | ||
_featureManager = featureManager; | ||
} | ||
|
||
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) | ||
{ | ||
if (!(await _featureManager.IsEnabledAsync(FeatureFlags.ApiKey))) | ||
{ | ||
return; | ||
} | ||
|
||
if (!context.HttpContext.Request.Headers.TryGetValue("Authorization", out var values)) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("Authorization header is missing"); | ||
return; | ||
} | ||
|
||
var authorization = values.FirstOrDefault(); | ||
if (string.IsNullOrWhiteSpace(authorization)) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("Authorization header is empty"); | ||
return; | ||
} | ||
|
||
var match = _apiKeyRegex.Match(authorization); | ||
if (!match.Success) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("ApiKey Authorization header value not match `ApiKey xxx-xxx`"); | ||
return; | ||
} | ||
|
||
var apiKeyValue = match.Groups["ApiKey"].Value; | ||
// you can look into DB as well | ||
if (_options.Value.SecretKey != apiKeyValue) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("ApiKey Unauthorized"); | ||
return; | ||
} | ||
} | ||
} | ||
} | ||
using System.Linq; | ||
using System.Text.RegularExpressions; | ||
using HappyCode.NetCoreBoilerplate.Api.Infrastructure.Configurations; | ||
using HappyCode.NetCoreBoilerplate.Core; | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.AspNetCore.Mvc.Filters; | ||
using Microsoft.Extensions.Options; | ||
using Microsoft.FeatureManagement; | ||
|
||
namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters | ||
{ | ||
public class ApiKeyAuthorizationFilter : IAsyncAuthorizationFilter | ||
{ | ||
private static readonly Regex _apiKeyRegex = new Regex(@"^[Aa][Pp][Ii][Kk][Ee][Yy]\s+(?<ApiKey>.+)$", RegexOptions.Compiled); | ||
|
||
private readonly IOptions<ApiKeySettings> _options; | ||
private readonly IFeatureManager _featureManager; | ||
|
||
public ApiKeyAuthorizationFilter(IOptions<ApiKeySettings> options, IFeatureManager featureManager) | ||
{ | ||
_options = options; | ||
_featureManager = featureManager; | ||
} | ||
|
||
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) | ||
{ | ||
if (!(await _featureManager.IsEnabledAsync(FeatureFlags.ApiKey))) | ||
{ | ||
return; | ||
} | ||
bool hasAllowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<IAllowAnonymous>().Any(); | ||
if (hasAllowAnonymous) | ||
{ | ||
return; | ||
} | ||
|
||
if (!context.HttpContext.Request.Headers.TryGetValue("Authorization", out var values)) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("Authorization header is missing"); | ||
return; | ||
} | ||
|
||
var authorization = values.FirstOrDefault(); | ||
if (string.IsNullOrWhiteSpace(authorization)) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("Authorization header is empty"); | ||
return; | ||
} | ||
|
||
var match = _apiKeyRegex.Match(authorization); | ||
if (!match.Success) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("ApiKey Authorization header value not match `ApiKey xxx-xxx`"); | ||
return; | ||
} | ||
|
||
var apiKeyValue = match.Groups["ApiKey"].Value; | ||
// you can look into DB as well | ||
if (_options.Value.SecretKey != apiKeyValue) | ||
{ | ||
context.Result = new UnauthorizedObjectResult("ApiKey Unauthorized"); | ||
return; | ||
} | ||
} | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
...etCoreBoilerplate.Api/Infrastructure/Filters/SecurityRequirementSwaggerOperationFilter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
using Microsoft.OpenApi.Models; | ||
using System.Linq; | ||
using Swashbuckle.AspNetCore.SwaggerGen; | ||
using Microsoft.AspNetCore.Authorization; | ||
|
||
namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters | ||
{ | ||
public class SecurityRequirementSwaggerOperationFilter : IOperationFilter | ||
{ | ||
public void Apply(OpenApiOperation operation, OperationFilterContext context) | ||
{ | ||
var hasAllowAnonymous = context.ApiDescription.CustomAttributes().OfType<IAllowAnonymous>().Any(); | ||
if (hasAllowAnonymous) | ||
{ | ||
return; | ||
} | ||
|
||
operation.Security.Add(new OpenApiSecurityRequirement | ||
{ | ||
{ | ||
new OpenApiSecurityScheme | ||
{ | ||
Name = "ApiKey", | ||
Type = SecuritySchemeType.ApiKey, | ||
In = ParameterLocation.Header, | ||
Reference = new OpenApiReference | ||
{ | ||
Type = ReferenceType.SecurityScheme, | ||
Id = "ApiKey", | ||
}, | ||
}, | ||
Array.Empty<string>() | ||
} | ||
}); | ||
} | ||
} | ||
} |
103 changes: 44 additions & 59 deletions
103
src/HappyCode.NetCoreBoilerplate.Api/Infrastructure/Registrations/SwaggerRegistration.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,59 +1,44 @@ | ||
using System.IO; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.OpenApi.Models; | ||
|
||
namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Registrations | ||
{ | ||
public static class SwaggerRegistration | ||
{ | ||
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration) | ||
{ | ||
string secretKey = configuration.GetValue<string>("ApiKey:SecretKey"); | ||
|
||
services.AddSwaggerGen(swaggerOptions => | ||
{ | ||
swaggerOptions.SwaggerDoc("v1", new OpenApiInfo | ||
{ | ||
Title = "Simple Api", | ||
Version = "v1", | ||
Description = $"ApiKey {secretKey}", | ||
Contact = new OpenApiContact | ||
{ | ||
Name = "Łukasz Kurzyniec", | ||
Url = new Uri("https://kurzyniec.pl/"), | ||
} | ||
}); | ||
swaggerOptions.OrderActionsBy(x => x.RelativePath); | ||
swaggerOptions.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HappyCode.NetCoreBoilerplate.Api.xml")); | ||
swaggerOptions.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme | ||
{ | ||
Description = "ApiKey needed to access the endpoints (eg: `Authorization: ApiKey xxx-xxx`)", | ||
In = ParameterLocation.Header, | ||
Name = "Authorization", | ||
Type = SecuritySchemeType.ApiKey, | ||
}); | ||
swaggerOptions.AddSecurityRequirement(new OpenApiSecurityRequirement | ||
{ | ||
{ | ||
new OpenApiSecurityScheme | ||
{ | ||
Name = "ApiKey", | ||
Type = SecuritySchemeType.ApiKey, | ||
In = ParameterLocation.Header, | ||
Reference = new OpenApiReference | ||
{ | ||
Type = ReferenceType.SecurityScheme, | ||
Id = "ApiKey", | ||
}, | ||
}, | ||
Array.Empty<string>() | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
} | ||
using System.IO; | ||
using HappyCode.NetCoreBoilerplate.Api.Infrastructure.Filters; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.OpenApi.Models; | ||
|
||
namespace HappyCode.NetCoreBoilerplate.Api.Infrastructure.Registrations | ||
{ | ||
public static class SwaggerRegistration | ||
{ | ||
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration) | ||
{ | ||
string secretKey = configuration.GetValue<string>("ApiKey:SecretKey"); | ||
|
||
services.AddSwaggerGen(swaggerOptions => | ||
{ | ||
swaggerOptions.SwaggerDoc("v1", new OpenApiInfo | ||
{ | ||
Title = "Simple Api", | ||
Version = "v1", | ||
Description = $"ApiKey {secretKey}", | ||
Contact = new OpenApiContact | ||
{ | ||
Name = "Łukasz Kurzyniec", | ||
Url = new Uri("https://kurzyniec.pl/"), | ||
} | ||
}); | ||
swaggerOptions.OrderActionsBy(x => x.RelativePath); | ||
swaggerOptions.IncludeXmlComments(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HappyCode.NetCoreBoilerplate.Api.xml")); | ||
swaggerOptions.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme | ||
{ | ||
Description = "ApiKey needed to access the endpoints (eg: `Authorization: ApiKey xxx-xxx`)", | ||
In = ParameterLocation.Header, | ||
Name = "Authorization", | ||
Type = SecuritySchemeType.ApiKey, | ||
}); | ||
swaggerOptions.OperationFilter<SecurityRequirementSwaggerOperationFilter>(); | ||
}); | ||
} | ||
} | ||
} |