Skip to content

Instantly share code, notes, and snippets.

@OliverRC
Created June 21, 2022 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OliverRC/650436fbae77371a55b84c646c35ba3a to your computer and use it in GitHub Desktop.
Save OliverRC/650436fbae77371a55b84c646c35ba3a to your computer and use it in GitHub Desktop.
Secure AspNetCore .NET 6 API with Auth0 - Works with SwaggerUI
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "https://<auth0-domain>/";
options.Audience = "https://<auth0-domain>/userinfo"; // or "<your audience>"
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Auth0", new OpenApiSecurityScheme()
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri("https://<auth0-domain>/authorize"),
TokenUrl = new Uri("https://<auth0-domain>/oauth/token"),
Scopes = new Dictionary<string, string>
{
{"openid", "openid"},
{"email", "email"},
{"profile", "profile"},
// any additional custom scopes you want
}
}
}
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
// optional: just prefills the Swagger UI input boxes, if left off you must supply these values. Would make sense to get these from configuration and better yet user-secrets
options.OAuthClientId("<auth0 client id>");
options.OAuthClientSecret("<auth0 client secret>");
// optional & gotcha: but if you are using Auth0 with a Social Connection you MUST supply an audience otherwise you will get back the underlying identity providers access token, NOT Auth0's
options.OAuthAdditionalQueryStringParams(new Dictionary<string, string>
{
{"audience", "<your audience>"}
});
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment