.Net Core 3.1, NSwag, and Auth0
Just a quick one, mostly a note to future self and anyone else struggling with what should be a simple setup of these three.
Setting up your app to accept the JWT tokens
Add the services;
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = $"https://{Configuration["Auth0:Authority"]}/";
options.Audience = Configuration["Auth0:Audience"];
});
And add it to the pipeline;
app.UseAuthentication();
app.UseAuthorization();
Setting up NSwag so it lets you authenticate and handles the attaching the token
services.AddOpenApiDocument(c =>
{
c.AddSecurity("oauth2", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.OAuth2,
Description = "Auth0 Auth",
Flow = OpenApiOAuth2Flow.Implicit,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
AuthorizationUrl = $"https://{Configuration["Auth0:Authority"]}/authorize?audience=whatever",
TokenUrl = $"https://{Configuration["Auth0:Authority"]}",
}
},
});
});
Please note the fact I have appended an audience
to the url. If you do not do this Auth0 will give you back an opaque token and not a JWT. This is super annoying as it's not mentioned anywhere in their docs about access tokens. Nor is it mentioned in this top google result in their community forums. I finally found the solution on another post with a dead link to their documentation. Yes, this was super frustrating. In fact this is what has inspired this blog note.