Below is the code that I use to do protected ASP.NET Core MVC login and protected api using the same project (for some reason). The problem is the API only has intended result when the user logged in. If getting them with the test token through curl in swagger UI, I see CORS error. For your reference, the razor views and api do only show results when the user logs in, and the useful codes are quoted here:
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
…
builder.Services.AddAuth0WebAppAuthentication(options =>
{
options.Domain = builder.Configuration\["Auth0:Domain"\];
options.ClientId = builder.Configuration\["Auth0:ClientId"\];
options.ClientSecret = builder.Configuration\["Auth0:ClientSecret"\];
})
.WithAccessToken(options =>
{
options.Audience = builder.Configuration\["Auth0:Audience"\];
});
builder.Services.AddAuth0ApiAuthentication("Auth",
Configuration.GetSection("Auth0"),
configureJwtBearer: jwt =>
{
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new\[\]
{
Configuration\["Auth0:Audience"\]
}
};
jwt.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var token = context.Request.Query\["access_token"\].FirstOrDefault();
if (string.IsNullOrEmpty(token))
{
token = context.Request.Headers\["X-API-Token"\].FirstOrDefault();
}
if (!string.IsNullOrEmpty(token))
{
context.Token = token;
}
return Task.CompletedTask;
}
};
}
);