Audience parameter is missing from Bearer Token while using Swagger (swashbuckle v5.3.1) with Asp.net Core 3.1.1 - asp.net-web-api2

Jwt Authentication section from Startup.cs:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = config["Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(config["RequireHttpsMetadata"]);
options.Authority = config["Authority"];
options.Audience = config["Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = config["Audience"],
ValidateAudience = Convert.ToBoolean(config["ValidateAudience"]),
ValidateIssuer = Convert.ToBoolean(config["ValidateIssuer"]),
};
});
Swagger configuration:
services.AddSwaggerGen(setup => {
setup.SwaggerDoc("1.0", new OpenApiInfo
{
Title = "Switchboard Live Cloud API v1.0",
Version = "1.0",
Description = "Programmable access to Switchboard Live's Cloud Platform.",
});
setup.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new System.Uri(string.Format("{0}/connect/authorize", authority)),
Scopes = new Dictionary<string, string> {
{ "read", "R" },
{ "write", "W" }
}
}
}
});
setup.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
},
new[] { "read", "write" }
}
});
.....
app.UseSwagger();
app.UseSwaggerUI(setup => {
setup.SwaggerEndpoint("/swagger/1.0/swagger.json", "Title");
setup.RoutePrefix = string.Empty;
});
I don't see what am I doing wrong here, but when I start the application, check the scopes and go through the authorization process, I end up with a Bearer Token that do NOT have the audience field encrypted in it, so all my requests ends up with a 401 Unauthorized response and the following header error:
www-authenticate: Bearer error="invalid_token", error_description="The audience 'empty' is invalid"
Any suggestions/solutions for this?

There was a major change in IdentityServer4 version v4 they are no longer setting the aud claim by default.
If you check the configuration section of the official documentation it says you need to disable the aud Claim:
https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html#configuration
So, you need set the property ValidateAudience = false with something like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
}

Related

Multiple JWT Tokens and Multiple Auth Handlers

I currently have Auth in place for my API application using a JWT token with Identity User, Which works great, I am now trying to chain on another JWT Token which users keycloak and I want to setup A custom auth Handler just for that token type, is that possible? My Code looks as follows:
services.AddAuthentication()
.AddJwtBearer("KeyCloak", opt =>
{
opt.Authority = "site.co.za/auth/realms/Development";
opt.Audience = "dev";
opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudiences = new string[] { "dev" },
NameClaimType = "preferred_username",
RoleClaimType = "role"
};
opt.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
}
};
opt.RequireHttpsMetadata = false;
opt.SaveToken = true;
opt.Validate();
})
.AddJwtBearer("Internal", opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Constants.AuthTokenKey))
};
});
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("KeyCloak", "Internal").Build();
});
I need to add a custom Auth HandleAuthenticateAsync just for keycloak and use the normal out of the box HandleAuthenticateAsync for internal. Is this possible to do?
You can do this:
this will select the jwt token validation based on API path.
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = "Custom";
})
.AddPolicyScheme("Custom", "Custom", options =>
{
options.ForwardDefaultSelector = context =>
{
bool isKeyCloakAuthRequired = context.Request.Path.StartsWithSegments("/apithatneedskeycloakauth");
if (isKeyCloakAuthRequired)
{
return "Keycloak";
}
else
{
return "Internal";
}
};
})
.AddJwtBearer("Keycloak", options =>
{
// your code for keycloak validation parameters.
})
.AddJwtBearer("Internal", options =>
{
// your code for token validation parameters.
})
Hope it helps.

ASP.NET Core 3.1: User.Identity.Name is empty in API Controller, but claim name is present

I'm adding Identity Server to my existing project. Basically I have everything in place, but when I do a request to the API, the User.Identity.Name is null. However the User.Identity.Claims contains the name claim:
I'm aware of the way of getting the user name by HttpContext.User.FindFirstValue(ClaimTypes.Name), but it would require a lot of code refactoring, so I'd rather avoid this way.
I configured the ApiResources in Identity server the following way:
public static IEnumerable<ApiResource> ApiResources => new[]
{
new ApiResource
{
Name = "my-api",
DisplayName = "My API",
Description = "My API",
Scopes = new List<string> { "my-api"},
UserClaims = new List<string> {
JwtClaimTypes.Email,
JwtClaimTypes.Name,
JwtClaimTypes.Subject,
JwtClaimTypes.Role,
}
}
};
and the client:
public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
// ...
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"name",
"roles",
"my-api",
}
}
};
Authentication setup in API project:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Authority = config["IdentityServer:Domain"];
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = config["IdentityServer:Domain"],
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "my-api");
});
});
Please advice what am I doing wrong?
The problem is that Microsoft and OpenID connect have different opinion on what the name of the "name" claim should be. So what you need to do is to tell the system what the name of the name claim is, by:
.AddJwtBearer(opt =>
{
...
opt.TokenValidationParameters.RoleClaimType = "roles";
opt.TokenValidationParameters.NameClaimType = "name";
...
}

Swagger JWT Authorization does not work in ASP.net core 3.1

I have this in my Startup.cs in the ConfigureServices:
services.ConfigureJwt(Configuration);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Backend.API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
I have this in my Startup.cs in the Configure:
app.UseCors("EnableCors");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
This is my service extension:
public static void ConfigureJwt(this IServiceCollection services, IConfiguration configuration)
{
var settings = new JwtSettings();
settings.Key = configuration["JwtSettings:key"];
settings.Audience = configuration["JwtSettings:audience"];
settings.Issuer = configuration["JwtSettings:issuer"];
settings.MinutesToExpiration = Convert.ToInt32(
configuration["JwtSettings:minutesToExpiration"]);
services.AddSingleton(settings);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", jwtBearerOptions =>
{
jwtBearerOptions.RequireHttpsMetadata = false;
jwtBearerOptions.SaveToken = true;
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = settings.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(settings.Key)),
ValidAudience = settings.Audience,
ClockSkew = TimeSpan.FromMinutes(
settings.MinutesToExpiration)
};
});
}
and in my Sagger UI login, this is the reply I get:
{
"userId": 1,
"userName": "user",
"firstName": "My FirstName",
"middleName": "A.",
"lastName": "My LastName",
"bearerToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqdWFuIiwianRpIjoiNmQwNjQ4ZWMtOGI4YS00YTBkLTlmYmItZTliYWFmNzdmZjI2IiwiVXNlcklkIjoiMSIsIkZpcnN0TmFtZSI6Imp1YW4iLCJNaWRkbGVOYW1lIjoiQS4iLCJMYXN0TmFtZSI6IkRlbGEgQ3J1eiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6WyJVc2VyIiwiQWRtaW4iXSwiZXhwIjoxNjA2OTc4MjcyLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDM2NiIsImF1ZCI6IkdlbmVyYWxUZW1wbGF0ZSJ9.MMnu-suoae7U3QnXJTa9wI2xDUtdDJTtc63KWyd3bZM",
"isAuthenticated": true,
"claims": [
"User",
"Admin"
]
}
Why is it that I still get this error whenever I try to run an endpoint with [Authorize(Roles = "Admin")]
access-control-allow-origin: *
date: Thu03 Dec 2020 06:42:05 GMT
server: Microsoft-IIS/10.0
status: 401
www-authenticate: Bearer
x-powered-by: ASP.NET
This is the endpoint I am trying to run:
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> AddCategory(Category model)
{
var cm = new CategoryManager(context);
var result = await cm.Create(model);
if (result > 0)
{
return StatusCode(StatusCodes.Status201Created, model);
}
return StatusCode(StatusCodes.Status400BadRequest, model);
}
I was having this issue because I was just copy and pasting the "bearerToken" value in the Authorize of swagger. What I should do is copy the "bearerToken" value but add "Bearer " at the beginning.

How to validate Cognito JWT with empty audience correctly and authenticate after?

I use aps.net core with JWT authentication and I found that aws cognito returns wrong token. Instead aud it returns client_id in access token.
I use Nuget libraries
AWSSDK.Core
AWSSDK.CognitoIdentityProvider
Amazon.Extensions.CognitoAuthentication
It was the same result. For examaple:
Access token is:
{
"sub": "9ed87b45-da04-4fda-bc74-XXXXXXXXXXXX",
"event_id": "469880d0-8b17-417a-88d7-XXXXXXXXXXXX",
"token_use": "access",
"scope": "aws.cognito.signin.user.admin",
"auth_time": 1583252488,
"iss": "https://cognito-idp.us-east-2.amazonaws.com/us-east-2_XXXXXXXX",
"exp": 1583256088,
"iat": 1583252488,
"jti": "c1ca9561-51ce-4b57-9f51-3355363fb4f6",
"client_id": "AppClientIDXXXXXXXXXXXXX",
"username": "testname"
}
After all I found that id token returns with 'aud'
{
"sub": "9ed87b45-da04-4fda-bc74-XXXXXXXXXXXX",
"aud": "AppClientIDXXXXXXXXXXXXX",
"email_verified": true,
"event_id": "469880d0-8b17-417a-88d7-XXXXXXXXXXXX",
"token_use": "id",
"auth_time": 1583252488,
"iss": "https://cognito-idp.us-east-2.amazonaws.com/us-east-2_XXXXXXXX",
"cognito:username": "testname",
"exp": 1583256088,
"iat": 1583252488,
"email": "testname#mail.no"
}
I used two way of adding jwt authentication. It didn't work for me.
Example 1:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
{
var json = new WebClient().DownloadString(parameters.ValidIssuer + "/.well-known/jwks.json");
return JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
},
ValidateIssuer = true,
ValidIssuer = $"https://cognito-idp.{region}.amazonaws.com/{poolId}",
ValidateAudience = true,
ValidAudience = appClientId,
};
});
Example 2:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = appClientId;
options.Authority = $"https://cognito-idp.{region}.amazonaws.com/{poolId}";
});
My authentication code
using AWSSDK.CognitoIdentityProvider
var initiateAuthRequest = new InitiateAuthRequest()
{
ClientId = myClientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
initiateAuthRequest.AuthParameters.Add("USERNAME", user.Username);
initiateAuthRequest.AuthParameters.Add("PASSWORD", user.Password);
var authResponse = await _cognitoIdentityProvider.InitiateAuthAsync(initiateAuthRequest);
using Amazon.Extensions.CognitoAuthentication
var provider = new AmazonCognitoIdentityProviderClient(new EnvironmentVariablesAWSCredentials(), myRegion);
var userPool = new CognitoUserPool(myPool, myClient, provider);
var usr = new CognitoUser(user.Username, myClient, userPool, provider);
AuthFlowResponse authResponse = await usr.StartWithSrpAuthAsync(
new InitiateSrpAuthRequest(){Password = user.Password}).ConfigureAwait(false);
How to get valid JWT token? How to validate token correctly?
Updated:
In Example 1 if I set ValidateAudience to false and removed ValidAudience I get 401 error
ValidateAudience = false,
//ValidAudience = appClientId
My Startup.cs is
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
var region = Configuration[Resources.AWSRegion];
var poolId = Configuration[Resources.AWSPoolId];
var appClientId = Configuration[Resources.AWSClientId];
services.AddSingleton<IAmazonCognitoIdentityProvider>(provider => new AmazonCognitoIdentityProviderClient(RegionEndpoint.USEast2)));
services.AddControllers();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
{
var json = new WebClient().DownloadString(parameters.ValidIssuer + "/.well-known/jwks.json");
return JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
},
ValidateIssuer = true,
ValidIssuer = $"https://cognito-idp.{region}.amazonaws.com/{poolId}",
ValidateAudience = true,
ValidAudience = appClientId
};
});
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseAuthentication();
}
}
This worked out for me, I used id token instead of access token
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = GetCognitoTokenValidationParams();
});
}
private TokenValidationParameters GetCognitoTokenValidationParams()
{
var cognitoIssuer = $"https://cognito-idp.{Configuration["AWS:Region"]}.amazonaws.com/{Configuration["AWS:UserPoolId"]}";
var jwtKeySetUrl = $"{cognitoIssuer}/.well-known/jwks.json";
var cognitoAudience = Configuration["AWS:UserPoolClientId"];
return new TokenValidationParameters
{
IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
{
// get JsonWebKeySet from AWS
var json = new WebClient().DownloadString(jwtKeySetUrl);
return JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
},
ValidIssuer = cognitoIssuer,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidAudience = cognitoAudience
};
}
I think it is because you use the access jwt token returned from Cognito during sign-in. Use id token instead.
return new Promise((resolve, reject) => {
return user.authenticateUser(authenticationDetails, {
onFailure: (err) => {
reject(err);
},
onSuccess: (result) => {
resolve(new SignInResponse(result.getIdToken().getJwtToken()));
},
});
});
I read several answers and the majority recomended setting
ValidateAudience = false
Since I didn't want to do that, because it will avoid validating the correct audience, I ended up defining AudienceValidator, to do it you have to define a delegate in the options when configuring your application. So in Startup you have to include this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Audience = configuration["AWS:Cognito:ClientId"];
options.Authority = configuration["AWS:Cognito:Authority"];
options.TokenValidationParameters.AudienceValidator = (audiences, securityToken, validationParameters) =>
{
//This is necessary because Cognito tokens doesn't have "aud" claim. Instead the audience is set in "client_id"
return validationParameters.ValidAudience.Contains(((JwtSecurityToken)securityToken).Payload["client_id"].ToString());
};
});
This will check that the claim "client_id" corresponds with the audience you're expecting
I had the same issue and I have found only one solution.
If you are going to use an access token to authenticate user, set
ValidateAudience = false,
//ValidAudience = appClientId
and add AuthenticationSchemes to Authorize filter like that:
[HttpGet]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<string> Test()
{
return await Task.Run(() => "hello world");
}
I have very similar code and it worked for me. Hope it helps for you as well.
Also you can replace this code:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
To that (just to simplify):
services.AddAuthentication("Bearer")

Auth0 + Swashbuckle .Net Core 2.2. Missing claims in jwt token when using SwaggerUI

I am making a ASP.Net Core WebApi which is authentication via Auth0. I am using Swagger and SwaggerUI and trying to authenticate from Swagger UI.
// Add authentication services
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("Auth0", options =>
{
// Set the authority to your Auth0 domain
options.Authority = $"https://{Configuration["Auth0:Authority"]}";
// Configure the Auth0 Client ID and Client Secret
options.ClientId = Configuration["Auth0:ClientId"];
options.ClientSecret = Configuration["Auth0:ClientSecret"];
// Set response type to code
options.ResponseType = "code";
// Configure the scope
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.SaveTokens = true;
// Set the callback path, so Auth0 will call back to http://localhost:3000/callback
// Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard
options.CallbackPath = new PathString("/callback");
// Configure the Claims Issuer to be Auth0
options.ClaimsIssuer = "Auth0";
// Saves tokens to the AuthenticationProperties
options.SaveTokens = true;
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = context =>
{
context.ProtocolMessage.SetParameter("audience", #"https://predictor-dev.api");
return Task.FromResult(0);
},
// handle the logout redirection
OnRedirectToIdentityProviderForSignOut = (context) =>
{
var logoutUri = $"https://{Configuration["Auth0:Authority"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";
var postLogoutUri = context.Properties.RedirectUri;
if (!string.IsNullOrEmpty(postLogoutUri))
{
if (postLogoutUri.StartsWith("/"))
{
// transform to absolute
var request = context.Request;
postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
}
logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
}
context.Response.Redirect(logoutUri);
context.HandleResponse();
return Task.CompletedTask;
}
};
})
.AddJwtBearer(options =>
{
options.Authority = Configuration["Auth0:Authority"];
options.Audience = Configuration["Auth0:Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/roles"
};
options.ClaimsIssuer = "Auth0";
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder
.WithOrigins(Configuration["FrontendBaseUrl"])
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Predictor API", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = $"{Configuration["Auth0:Authority"]}authorize?audience={Configuration["Auth0:Audience"]}",
Scopes = new Dictionary<string, string>
{
{ "read:books", "Access read book operations" },
{ "write:books", "Access write book operations" }
}
});
c.OperationFilter<SecurityRequirementsOperationFilter>();
});
Here is the token which is returned after authentication via SwaggerUI:
{
"iss": "my iss",
"sub": "my sub",
"aud": "my aud",
"iat": 1556002815,
"exp": 1556010015,
"azp": "azp",
"scope": "read:books"
}
The problem here is that token doesn't have openid and profile information.
I don't have any custom rules in Auth0 that could limit my scopes (I removed them totally).I tried different options, but I could not get any additional claims.
Is there any configuration in Swagger that I am missing?
Thank you.
You have to pass "openid" and "profile" scopes to extend your token with openid and profile information