Getting Auth0 and Swagger to work

I have an ASP.NET Core API and I’m wanting to use Auth0 and Swagger. I have Swagger configured (using OAuth2) and can now login to Auth0 via Swagger.

I’ve also configured my API to use JwtBearerAuthentication according to https://auth0.com/docs/quickstart/backend/aspnet-core-webapi

However, when I try and access my operation I get the following error:

Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: IkrS18IDUwGEkvDw

Does anyone have any suggestions as to what I may be doing wrong?

1 Like

The sample token you provided is not a JWT access token so this hints at the root cause of the issue. The flow you performed through Swagger resulted in an access token that is not suitable to call your API.

When using the API Authorization functionality, Auth0 expects an audience parameter to be included in the request as a way to signal for which resource server (aka API) the access token is meant. At this time, an access token issued to your own configured API will be a JWT, however, if an audience is not provided it is assumed that the access token is meant only to retrieve user information at Auth0 and as such an opaque access token (currently 16 characters) is issued.

In order to resolve your situation you need to ensure that the audience parameter containing the identifier of the API in question is passed during the OAuth2 request. Have in mind that the audience parameter is not part of the core OAuth2 specification, although it appears in some extensions, so some software or libraries may not have built-in support for it. If Swagger does not have support to pass additional parameters it may be possible to specify an authorization endpoint URL that already contains that parameter. If the library behaves correctly it should maintain the existing query parameter and add the OAuth2 specific ones, more specifically, provide an authorization URL similar to:

https://[your_account].auth0.com/authorize?audience=[your_api_audience]

instead of just:

https://[your_account].auth0.com/authorize

If by any chance the library does not support a query parameter in the authorization endpoint (it should, as this is contemplated in the core specification) then you have one final option that may or may not address your specific scenario. In your account settings at Auth0 you can configure a default audience which means any request that does not include an explicit audience will be treated as if it contained the default one. This may or may not be acceptable to your particular situation as it will have a global impact.

2 Likes

I encountered the same issue thankfully you can pass extra query parameters via optional parameter on the ConfigureOAuth2 method. The following worked for me:

c.ConfigureOAuth2("your-client-id", null, null, null, " ", new { audience = "your-audience" });