I've a small C# application project based on WebAPI with Razor pages and .NET 8.0. It should just serve as a small application to manage the landing page for the users that sign on our MS Azure Marketplace. The setup code is the following:
var builder = WebApplication.CreateBuilder(args);
Startup startup = new(builder.Configuration);
startup.ConfigureService(builder.Services);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCookiePolicy(new CookiePolicyOptions
{
Secure = CookieSecurePolicy.Always
//MinimumSameSitePolicy = SameSiteMode.None,
//HttpOnly = HttpOnlyPolicy.None
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
....
....
....
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public void ConfigureService(IServiceCollection services)
{
//Configure AAD and Graph integration
services.AddMicrosoftIdentityWebAppAuthentication(Configuration!)//Sign on with Azure ADD
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })//Calls Graph API
.AddMicrosoftGraph()//Use default with Graph v1
.AddInMemoryTokenCaches();//Add token caching
//Configure OpenIDConnect
services.Configure<OpenIdConnectOptions>(
options => options.Events.OnSignedOutCallbackRedirect =
context =>
{
context.Response.Redirect("/");
context.HandleResponse();
return Task.CompletedTask;
}
);
//Validate JWT attributes
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme,
options => {
options.TokenValidationParameters.ValidAudience = this.Configuration["MarketplaceApi:ClientId"];
options.TokenValidationParameters.ValidIssuer = $"https://sts.windows.net/{this.Configuration["MarketplaceApi:TenantId"]}";
});
//Add the marketplace service
ConfigureMarketplaceServices(services);
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages()
.AddMicrosoftIdentityUI();
services.AddDbContext<AzureMarketplaceDbContext>(options => options.UseSqlServer("name=ConnectionStrings:AzureMarketplaceMSSql"));
}
private void ConfigureMarketplaceServices(IServiceCollection services)
{
var tenantId = Configuration["MarketplaceApi:TenantId"];
var clientId = Configuration["MarketplaceApi:ClientId"];
var clientSecret = Configuration["MarketplaceApi:ClientSecret"];
//Standards Azure credentials
var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret);
//CReates MarketplaceSaaSClient object to be injected
services.TryAddScoped<IMarketplaceSaaSClient>(sp =>
{
return new MarketplaceSaaSClient(credentials);
});
}
}
When I run in debug the application locally it correctly opens the login page where I can sign in without any issue. But if I try to run it using Visual Studio 2022 tunnelling in order to see if the landing page is correctly called from MS Azure, I get the following exception immediately after logging in:
And the log shows the following errors:
Is there anyone that has an idea on how to fix it ? Thank you in advance.
**** UPDATE *****
Configuration file (appsettings.json):
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "MyCompany.com",
"TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx",
"ClientId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
"ClientSecret": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath": "/signout-callback-oidc"
},
"MarketplaceApi": {
"ClientId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy",
"ClientSecret": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
"TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"AzureMarketplaceMSSql": "Server=ssssssssss;Database=jjjjjjjjjjjj;User ID=sa;Password=kkkkkkkkkkkk;TrustServerCertificate=True"
},
"AllowedHosts": "*"
}
**** BROWSER ERROR ****
An unhandled exception occurred while processing the request. AuthenticationFailureException: Correlation failed. Unknown location
AuthenticationFailureException: An error was encountered while handling the remote login. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()
Microsoft.AspNetCore.Authentication.AuthenticationFailureException: Correlation failed.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync() Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
Show raw exception details Microsoft.AspNetCore.Authentication.AuthenticationFailureException: An error was encountered while handling the remote login. ---> Microsoft.AspNetCore.Authentication.AuthenticationFailureException: Correlation failed. --- End of inner exception stack trace --- at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
**** LOG FILE ERROR ****
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[15] '.AspNetCore.Correlation.zoY7cLioLI9dUlmbF94ZwZvXNx2o8kl8ih9hurzCyd4' cookie not found. fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware1 An unhandled exception has occurred while executing the request. Microsoft.AspNetCore.Authentication.AuthenticationFailureException: An error was encountered while handling the remote login. ---> Microsoft.AspNetCore.Authentication.AuthenticationFailureException: Correlation failed. --- End of inner exception stack trace --- at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

