|
| 1 | +using AspNetCore.Authentication.ApiKey; |
| 2 | +using Microsoft.AspNetCore.Authorization; |
| 3 | +using SampleWebApi.Repositories; |
| 4 | +using SampleWebApi.Services; |
| 5 | + |
| 6 | +var builder = WebApplication.CreateBuilder(args); |
| 7 | + |
| 8 | +// Add User repository to the dependency container. |
| 9 | +builder.Services.AddTransient<IApiKeyRepository, InMemoryApiKeyRepository>(); |
| 10 | + |
| 11 | +// Add the ApiKey scheme authentication here.. |
| 12 | +// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set. |
| 13 | +// If an implementation of IApiKeyProvider interface is registered in the dependency register as well as OnValidateKey delegete on options.Events is also set then this delegate will be used instead of an implementation of IApiKeyProvider. |
| 14 | +builder.Services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme) |
| 15 | + |
| 16 | + // The below AddApiKeyInHeaderOrQueryParams without type parameter will require OnValidateKey delegete on options.Events to be set unless an implementation of IApiKeyProvider interface is registered in the dependency register. |
| 17 | + // Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.* |
| 18 | + //.AddApiKeyInHeaderOrQueryParams(options => |
| 19 | + |
| 20 | + // The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency register. |
| 21 | + // Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider. |
| 22 | + .AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options => |
| 23 | + { |
| 24 | + options.Realm = "Sample Web API"; |
| 25 | + options.KeyName = "X-API-KEY"; |
| 26 | + |
| 27 | + //// Optional option to suppress the browser login dialog for ajax calls. |
| 28 | + //options.SuppressWWWAuthenticateHeader = true; |
| 29 | + |
| 30 | + //// Optional option to ignore extra check of ApiKey string after it is validated. |
| 31 | + //options.ForLegacyIgnoreExtraValidatedApiKeyCheck = true; |
| 32 | + |
| 33 | + //// Optional option to ignore authentication if AllowAnonumous metadata/filter attribute is added to an endpoint. |
| 34 | + //options.IgnoreAuthenticationIfAllowAnonymous = true; |
| 35 | + |
| 36 | + //// Optional events to override the ApiKey original logic with custom logic. |
| 37 | + //// Only use this if you know what you are doing at your own risk. Any of the events can be assigned. |
| 38 | + options.Events = new ApiKeyEvents |
| 39 | + { |
| 40 | + |
| 41 | + //// A delegate assigned to this property will be invoked just before validating the api key. |
| 42 | + //OnValidateKey = async (context) => |
| 43 | + //{ |
| 44 | + // // custom code to handle the api key, create principal and call Success method on context. |
| 45 | + // var apiKeyRepository = context.HttpContext.RequestServices.GetRequiredService<IApiKeyRepository>(); |
| 46 | + // var apiKey = await apiKeyRepository.GetApiKeyAsync(context.ApiKey); |
| 47 | + // var isValid = apiKey != null && apiKey.Key.Equals(context.ApiKey, StringComparison.OrdinalIgnoreCase); |
| 48 | + // if (isValid) |
| 49 | + // { |
| 50 | + // context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateKey"); |
| 51 | + // var claims = new[] |
| 52 | + // { |
| 53 | + // new Claim(ClaimTypes.NameIdentifier, apiKey.OwnerName, ClaimValueTypes.String, context.Options.ClaimsIssuer), |
| 54 | + // new Claim(ClaimTypes.Name, apiKey.OwnerName, ClaimValueTypes.String, context.Options.ClaimsIssuer), |
| 55 | + // new Claim("CustomClaimType", "Custom Claim Value - from OnValidateKey") |
| 56 | + // }; |
| 57 | + // context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name)); |
| 58 | + // context.Success(); |
| 59 | + // } |
| 60 | + // else |
| 61 | + // { |
| 62 | + // context.NoResult(); |
| 63 | + // } |
| 64 | + //}, |
| 65 | + |
| 66 | + //// A delegate assigned to this property will be invoked just before validating the api key. |
| 67 | + //// NOTE: Same as above delegate but slightly different implementation which will give same result. |
| 68 | + //OnValidateKey = async (context) => |
| 69 | + //{ |
| 70 | + // // custom code to handle the api key, create principal and call Success method on context. |
| 71 | + // var apiKeyRepository = context.HttpContext.RequestServices.GetRequiredService<IApiKeyRepository>(); |
| 72 | + // var apiKey = await apiKeyRepository.GetApiKeyAsync(context.ApiKey); |
| 73 | + // var isValid = apiKey != null && apiKey.Key.Equals(context.ApiKey, StringComparison.OrdinalIgnoreCase); |
| 74 | + // if (isValid) |
| 75 | + // { |
| 76 | + // context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateKey"); |
| 77 | + // var claims = new[] |
| 78 | + // { |
| 79 | + // new Claim("CustomClaimType", "Custom Claim Value - from OnValidateKey") |
| 80 | + // }; |
| 81 | + // context.ValidationSucceeded(apiKey.OwnerName, claims); // claims are optional |
| 82 | + // } |
| 83 | + // else |
| 84 | + // { |
| 85 | + // context.ValidationFailed(); |
| 86 | + // } |
| 87 | + //}, |
| 88 | + |
| 89 | + //// A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response. |
| 90 | + //OnHandleChallenge = async (context) => |
| 91 | + //{ |
| 92 | + // // custom code to handle authentication challenge unauthorized response. |
| 93 | + // context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
| 94 | + // context.Response.Headers.Add("ChallengeCustomHeader", "From OnHandleChallenge"); |
| 95 | + // await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleChallenge\"}"); |
| 96 | + // context.Handled(); // important! do not forget to call this method at the end. |
| 97 | + //}, |
| 98 | + |
| 99 | + //// A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response. |
| 100 | + //OnHandleForbidden = async (context) => |
| 101 | + //{ |
| 102 | + // // custom code to handle forbidden response. |
| 103 | + // context.Response.StatusCode = StatusCodes.Status403Forbidden; |
| 104 | + // context.Response.Headers.Add("ForbidCustomHeader", "From OnHandleForbidden"); |
| 105 | + // await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleForbidden\"}"); |
| 106 | + // context.Handled(); // important! do not forget to call this method at the end. |
| 107 | + //}, |
| 108 | + |
| 109 | + //// A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateKey delegate is assigned. |
| 110 | + //// It can be used for adding claims, headers, etc to the response. |
| 111 | + //OnAuthenticationSucceeded = (context) => |
| 112 | + //{ |
| 113 | + // //custom code to add extra bits to the success response. |
| 114 | + // context.Response.Headers.Add("SuccessCustomHeader", "From OnAuthenticationSucceeded"); |
| 115 | + // var customClaims = new List<Claim> |
| 116 | + // { |
| 117 | + // new Claim("CustomClaimType", "Custom Claim Value - from OnAuthenticationSucceeded") |
| 118 | + // }; |
| 119 | + // context.AddClaims(customClaims); |
| 120 | + // //or can add like this - context.Principal.AddIdentity(new ClaimsIdentity(customClaims)); |
| 121 | + // return Task.CompletedTask; |
| 122 | + //}, |
| 123 | + |
| 124 | + //// A delegate assigned to this property will be invoked when the authentication fails. |
| 125 | + //OnAuthenticationFailed = (context) => |
| 126 | + //{ |
| 127 | + // // custom code to handle failed authentication. |
| 128 | + // context.Fail("Failed to authenticate"); |
| 129 | + // return Task.CompletedTask; |
| 130 | + //} |
| 131 | + |
| 132 | + }; |
| 133 | + }); |
| 134 | + |
| 135 | +builder.Services.AddControllers(options => |
| 136 | +{ |
| 137 | + // ALWAYS USE HTTPS (SSL) protocol in production when using ApiKey authentication. |
| 138 | + //options.Filters.Add<RequireHttpsAttribute>(); |
| 139 | + |
| 140 | +}); //.AddXmlSerializerFormatters() // To enable XML along with JSON; |
| 141 | + |
| 142 | +// All the requests will need to be authorized. |
| 143 | +// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary. |
| 144 | +builder.Services.AddAuthorizationBuilder() |
| 145 | + .AddFallbackPolicy( |
| 146 | + "FallbackPolicy", |
| 147 | + new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() |
| 148 | + ); |
| 149 | + |
| 150 | +var app = builder.Build(); |
| 151 | + |
| 152 | +// Configure the HTTP request pipeline. |
| 153 | + |
| 154 | +app.UseHttpsRedirection(); |
| 155 | + |
| 156 | +app.UseAuthentication(); // NOTE: DEFAULT TEMPLATE DOES NOT HAVE THIS, THIS LINE IS REQUIRED AND HAS TO BE ADDED!!! |
| 157 | + |
| 158 | +app.UseAuthorization(); |
| 159 | + |
| 160 | +app.MapControllers(); |
| 161 | + |
| 162 | +app.Run(); |
0 commit comments