Skip to content

Instantly share code, notes, and snippets.

@droyad
Created December 19, 2022 03:52
Show Gist options
  • Save droyad/0309fb7e5b01101ba56b111a58c8b5bf to your computer and use it in GitHub Desktop.
Save droyad/0309fb7e5b01101ba56b111a58c8b5bf to your computer and use it in GitHub Desktop.
services.AddAuthentication(options =>
{
// custom scheme defined in .AddPolicyScheme() below
options.DefaultScheme = "JwtOrApiKey";
options.DefaultChallengeScheme = "JwtOrApiKey";
})
.AddPolicyScheme("JwtOrApiKey", "JwtOrApiKey", options =>
{
// runs on each request
options.ForwardDefaultSelector = context =>
{
var authorization = context.Request.Headers.Authorization.ToString();
if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer "))
return JwtBearerDefaults.AuthenticationScheme;
return ApiKeyAuthenticationOptions.ApiKeyScheme;
};
})
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.ApiKeyScheme, null, null)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("ApiAzureAd"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment