Created
November 19, 2023 08:00
-
-
Save cashwu/5b9e1698bc5d884a87d434040a512d8d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| public class ApiKeyAttribute : ServiceFilterAttribute | |
| { | |
| public ApiKeyAttribute() | |
| : base(typeof(ApiKeyAuthorizationFilter)) | |
| { | |
| } | |
| } | |
| public class ApiKeyAuthorizationFilter : IAuthorizationFilter | |
| { | |
| private const string ApiKeyHeaderName = "X-API-Key"; | |
| private readonly IApiKeyValidator _apiKeyValidator; | |
| public ApiKeyAuthorizationFilter(IApiKeyValidator apiKeyValidator) | |
| { | |
| _apiKeyValidator = apiKeyValidator; | |
| } | |
| public void OnAuthorization(AuthorizationFilterContext context) | |
| { | |
| string apiKey = context.HttpContext.Request.Headers[ApiKeyHeaderName]; | |
| if (!_apiKeyValidator.IsValid(apiKey)) | |
| { | |
| context.Result = new UnauthorizedResult(); | |
| } | |
| } | |
| } | |
| public class ApiKeyValidator : IApiKeyValidator | |
| { | |
| public bool IsValid(string apiKey) | |
| { | |
| // Implement logic for validating the API key. | |
| } | |
| } | |
| public interface IApiKeyValidator | |
| { | |
| bool IsValid(string apiKey); | |
| } | |
| { | |
| builder.Services.AddSingleton<ApiKeyAuthorizationFilter>(); | |
| builder.Services.AddSingleton<IApiKeyValidator, ApiKeyValidator>(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment