Azure-Samples / active-directory-aspnetcore-webapp-openidconnect-v2

An ASP.NET Core Web App which lets sign-in users (including in your org, many orgs, orgs + personal accounts, sovereign clouds) and call Web APIs (including Microsoft Graph)
MIT License
1.37k stars 990 forks source link

SQL distributed cache fails with Login failed for user ''. #366

Closed multco-malan closed 2 years ago

multco-malan commented 4 years ago

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

The issue was found for the following scenario:

Please add an 'x' for the scenario(s) where you found an issue

  1. Web app that signs in users
    1. [ ] with a work and school account in your organization: 1-WebApp-OIDC/1-1-MyOrg
    2. [ ] with any work and school account: /1-WebApp-OIDC/1-2-AnyOrg
    3. [ ] with any work or school account or Microsoft personal account: 1-WebApp-OIDC/1-3-AnyOrgOrPersonal
    4. [ ] with users in National or sovereign clouds 1-WebApp-OIDC/1-4-Sovereign
    5. [ ] with B2C users 1-WebApp-OIDC/1-5-B2C
  2. Web app that calls Microsoft Graph
    1. [ ] Calling graph with the Microsoft Graph SDK: 2-WebApp-graph-user/2-1-Call-MSGraph
    2. [X] With specific token caches: 2-WebApp-graph-user/2-2-TokenCache
    3. [ ] Calling Microsoft Graph in national clouds: 2-WebApp-graph-user/2-4-Sovereign-Call-MSGraph
  3. [ ] Web app calling several APIs 3-WebApp-multi-APIs
  4. [ ] Web app calling your own Web API 4-WebApp-your-API
  5. Web app restricting users
    1. [ ] by Roles: 5-WebApp-AuthZ/5-1-Roles
    2. [ ] by Groups: 5-WebApp-AuthZ/5-2-Groups
  6. [ ] Deployment to Azure
  7. [ ] Other (please describe)

Repro-ing the issue

Running my web application locally attempting to use DistributedSqlServerCache fails with "Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user ''."

I am using the exact same SQL connection string as the rest of the app. Once I get this working I may move the token cache table to a different database.

The database is a sql database in Azure.

Before I attempted to add the SQL cache, everything connecting to the database succeeds when running locally against an Azure sql db, including the apps pages and EF migrations.

here is my configure services:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient();
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.HandleSameSiteCookieCompatibility();
            });
            services.AddOptions();

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme);
            services.AddSignIn(
                configureOpenIdConnectOptions: options =>
                    {
                        Configuration.Bind("AzureAd", options);
                        var existingOnAuthorizationCodeReceivedHandler = options.Events.OnAuthorizationCodeReceived;
                        options.Events.OnAuthorizationCodeReceived = async context =>
                        {
                            await existingOnAuthorizationCodeReceivedHandler(context);
                            await OnAuthorizationCodeReceived(context);
                        };
                    },
                configureMicrosoftIdentityOptions: options =>
                    {
                        Configuration.Bind("AzureAd", options);
                    }
                )
                .AddWebAppCallsProtectedWebApi(Configuration, new string[] { graphScopes })
                .AddDistributedTokenCaches();

// including the below fails w/ Login failed for user ''.
            //services.AddDistributedSqlServerCache(options => { 
            //    options.ConnectionString = Configuration["ConnectionStrings:SmsTextingContext"];
            //    options.SchemaName = "dbo";
            //    options.TableName = "TokenCache";
            //});

            services.AddSingleton<IAuthorizationHandler, MsrCheckIdParameterHandler>();
            services.AddSingleton<IAuthorizationHandler, MsrCheckIdForAdminOrManagerParameterHandler>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.Admin, policy => policy.RequireClaim(ClaimTypes.Role, ActiveDirectoryGroupName_ADMIN));
                options.AddPolicy(Policies.AdminOrManager,
                    policy => policy.RequireAssertion(context =>
                        context.User.HasClaim(claim =>
                            context.User.IsInRole(ActiveDirectoryGroupName_ADMIN)
                            )));
                options.AddPolicy(Policies.Nobody, policy => policy.RequireClaim(ClaimTypes.Role, "NOBODY"));
                options.AddPolicy(Policies.UserMayAccessMsr, policy => policy.Requirements.Add(new UserHasMsrPermission()));
                options.AddPolicy(Policies.AdminOrManagerOnly, policy => policy.Requirements.Add(new UserIsAdminOrManagerPermission()));
            });

            services.AddMSGraphService(Configuration);
            services.AddTextMessagingService(Configuration);
            services.AddTwilioCallbackService(Configuration);
            services.AddTransient<ClaimsService>();

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI();

            services.AddRazorPages()
                .AddRazorPagesOptions(o =>
                {
                    o.Conventions.AllowAnonymousToFolder("/Public");
                });
            services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddDbContext<SmsTextingContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SmsTextingContext"));
            });
            _logger.LogInformation(Configuration.GetConnectionString("SmsTextingContext"));
            var DoNotPerformEFMigrations = Environment.GetEnvironmentVariable("DoNotPerformEFMigrations");
            _logger.LogInformation("DoNotPerformEFMigrations = " + DoNotPerformEFMigrations);

            ApplyEFMigrations(services);

            services.AddScoped<AuthorizationsService>();
            services.AddScoped<DatabaseService>();
        }

Here is stack trace:

System.Net.Http.HttpClient.Default.LogicalHandler: Information: Start processing HTTP request GET https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https%3A%2F%2Flogin.microsoftonline.com%2FmyTenant%2Foauth2%2Fv2.0%2Fauthorize
System.Net.Http.HttpClient.Default.ClientHandler: Information: Sending HTTP request GET https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https%3A%2F%2Flogin.microsoftonline.com%2FmyTenant%2Foauth2%2Fv2.0%2Fauthorize
System.Net.Http.HttpClient.Default.ClientHandler: Information: Received HTTP response after 141.7722ms - OK
System.Net.Http.HttpClient.Default.LogicalHandler: Information: End processing HTTP request after 150.2876ms - OK
System.Net.Http.HttpClient.Default.LogicalHandler: Information: Start processing HTTP request POST https://login.microsoftonline.com/<myTenant>/oauth2/v2.0/token
System.Net.Http.HttpClient.Default.ClientHandler: Information: Sending HTTP request POST https://login.microsoftonline.com/<myTenant>/oauth2/v2.0/token
System.Net.Http.HttpClient.Default.ClientHandler: Information: Received HTTP response after 287.8343ms - OK
System.Net.Http.HttpClient.Default.LogicalHandler: Information: End processing HTTP request after 291.2139ms - OK
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.3\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.3\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler: Error: Exception occurred while processing message.

Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user ''.
   at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) Windows 10

Versions

of ASP.NET Core, of MSAL.NET Core 3.1.3 Microsoft.Identity.Web and Web.UI 0.1.4-preview Microsoft.Extensions.Caching.SqlServer 3.1.5

TiagoBrenck commented 4 years ago

Hi @multco-malan

Is this error happening locally(using a local SQL db) or just when you deploy it?

multco-malan commented 4 years ago

@TiagoBrenck I am running the web app locally (Visual Studio 2019) and connecting to an Azure SQL database. I haven't gotten to deployment yet, gotta get it working locally before I even commit code.

TiagoBrenck commented 4 years ago

I see. Did you run the dotnet sql-cache create command? Update the connect string according to your settings.

dotnet tool install --global dotnet-sql-cache
dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MY_TOKEN_CACHE_DATABASE;Integrated Security=True;" dbo TokenCache

Note that this command only creates the table. In the example above, MY_TOKEN_CACHE_DATABASE should exist in prior.

multco-malan commented 4 years ago

@TiagoBrenck I tried that tool, but it failed for some reason I don't remember. I created a EF migration to create the table, getting it's structure from https://github.com/dotnet/aspnetcore/blob/4928eb3de0d80570dad93a143b52a8f5a205dac7/src/Tools/dotnet-sql-cache/src/SqlQueries.cs

Here is the generate table script I just generated from my azure sql db:

/****** Object:  Table [dbo].[TokenCache]    Script Date: 6/16/2020 2:02:07 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[TokenCache](
    [Id] [nvarchar](449) NOT NULL,
    [Value] [varbinary](max) NOT NULL,
    [ExpiresAtTime] [datetimeoffset](7) NOT NULL,
    [SlidingExpirationInSeconds] [bigint] NULL,
    [AbsoluteExpiration] [datetimeoffset](7) NULL,
 CONSTRAINT [pk_Id] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
TiagoBrenck commented 4 years ago

Ok, that is good then. This error is then related to your web config. Double check if the values are all fine.

I noticed that you are using:

options.ConnectionString = Configuration["ConnectionStrings:SmsTextingContext"];

while in another code, you have this:

Configuration.GetConnectionString("SmsTextingContext")

Declare a variable that receives the code that you are using for the connection string, and check if that variable got set properly. This "." in the error message usually is because it didnt get the connection string properly.

multco-malan commented 4 years ago

@TiagoBrenck I modified the code to this

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient();
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.HandleSameSiteCookieCompatibility();
            });
            services.AddOptions();

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme);
            services.AddSignIn(
                configureOpenIdConnectOptions: options =>
                    {
                        Configuration.Bind("AzureAd", options);
                        var existingOnAuthorizationCodeReceivedHandler = options.Events.OnAuthorizationCodeReceived;
                        options.Events.OnAuthorizationCodeReceived = async context =>
                        {
                            await existingOnAuthorizationCodeReceivedHandler(context);
                            await OnAuthorizationCodeReceived(context);
                        };
                    },
                configureMicrosoftIdentityOptions: options =>
                    {
                        Configuration.Bind("AzureAd", options);
                    }
                )
                .AddWebAppCallsProtectedWebApi(Configuration, new string[] { graphScopes })
                .AddDistributedTokenCaches();
            var connstr = Configuration.GetConnectionString("SmsTextingContext");
            services.AddDistributedSqlServerCache(options => {
                options.ConnectionString = connstr; // Configuration.GetConnectionString("SmsTextingContext");
                options.SchemaName = "dbo";
                options.TableName = "TokenCache";
            });

            services.AddSingleton<IAuthorizationHandler, MsrCheckIdParameterHandler>();
            services.AddSingleton<IAuthorizationHandler, MsrCheckIdForAdminOrManagerParameterHandler>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.Admin, policy => policy.RequireClaim(ClaimTypes.Role, ActiveDirectoryGroupName_ADMIN));
                options.AddPolicy(Policies.AdminOrManager,
                    policy => policy.RequireAssertion(context =>
                        context.User.HasClaim(claim =>
                            context.User.IsInRole(ActiveDirectoryGroupName_ADMIN)
                            )));
                options.AddPolicy(Policies.Nobody, policy => policy.RequireClaim(ClaimTypes.Role, "NOBODY"));
                options.AddPolicy(Policies.UserMayAccessMsr, policy => policy.Requirements.Add(new UserHasMsrPermission()));
                options.AddPolicy(Policies.AdminOrManagerOnly, policy => policy.Requirements.Add(new UserIsAdminOrManagerPermission()));
            });

            services.AddMSGraphService(Configuration);
            services.AddTextMessagingService(Configuration);
            services.AddTwilioCallbackService(Configuration);
            services.AddTransient<ClaimsService>();

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI();

            services.AddRazorPages()
                .AddRazorPagesOptions(o =>
                {
                    o.Conventions.AllowAnonymousToFolder("/Public");
                });
            services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddDbContext<SmsTextingContext>(options =>
            {
                //options.UseSqlServer(Configuration.GetConnectionString("SmsTextingContext"));
                options.UseSqlServer(connstr);
            });
            _logger.LogInformation(Configuration.GetConnectionString("SmsTextingContext"));
            var DoNotPerformEFMigrations = Environment.GetEnvironmentVariable("DoNotPerformEFMigrations");
            _logger.LogInformation("DoNotPerformEFMigrations = " + DoNotPerformEFMigrations);

            ApplyEFMigrations(services);

            services.AddScoped<AuthorizationsService>();
            services.AddScoped<DatabaseService>();
        }

the value of connstr is "Server=tcp:mc-ent-textmessaging-dev.database.usgovcloudapi.net,1433;Database=mc-ent-textSMS-dev;"

Same result, output below.

If I comment out the services.AddDistributedSqlServerCache() line, then I see that the app is correctly connecting to the database

Do you have any other thoughts/ideas?

I'm off on vacation and will be returning 2020-06-29.

Thanks for your help!

iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.3\System.Reflection.TypeExtensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Users\miersa\source\repos\mc-sdis\multco_eComm\WebAndApi-IncludingGraphApi\SmsWeb\bin\Debug\netcoreapp3.1\Microsoft.IdentityModel.JsonWebTokens.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.3\System.Security.Cryptography.Cng.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The thread 0x4c8c has exited with code 0 (0x0).
The thread 0x4e38 has exited with code 0 (0x0).
The thread 0x4ca0 has exited with code 0 (0x0).
System.Net.Http.HttpClient.Default.LogicalHandler: Information: Start processing HTTP request GET https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https%3A%2F%2Flogin.microsoftonline.com%2Ff588e3bf-7667-4650-957d-27663ccb0912%2Foauth2%2Fv2.0%2Fauthorize
System.Net.Http.HttpClient.Default.ClientHandler: Information: Sending HTTP request GET https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https%3A%2F%2Flogin.microsoftonline.com%2Ff588e3bf-7667-4650-957d-27663ccb0912%2Foauth2%2Fv2.0%2Fauthorize
System.Net.Http.HttpClient.Default.ClientHandler: Information: Received HTTP response after 135.7205ms - OK
System.Net.Http.HttpClient.Default.LogicalHandler: Information: End processing HTTP request after 145.2765ms - OK
System.Net.Http.HttpClient.Default.LogicalHandler: Information: Start processing HTTP request POST https://login.microsoftonline.com/f588e3bf-7667-4650-957d-27663ccb0912/oauth2/v2.0/token
System.Net.Http.HttpClient.Default.ClientHandler: Information: Sending HTTP request POST https://login.microsoftonline.com/f588e3bf-7667-4650-957d-27663ccb0912/oauth2/v2.0/token
System.Net.Http.HttpClient.Default.ClientHandler: Information: Received HTTP response after 438.3856ms - OK
System.Net.Http.HttpClient.Default.LogicalHandler: Information: End processing HTTP request after 442.2551ms - OK
The thread 0x4564 has exited with code 0 (0x0).
The thread 0x3dd8 has exited with code 0 (0x0).
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.3\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.3\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler: Error: Exception occurred while processing message.

Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user ''.
   at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Extensions.Caching.SqlServer.DatabaseOperations.SetCacheItemAsync(String key, Byte[] value, DistributedCacheEntryOptions options, CancellationToken token)
   at Microsoft.Extensions.Caching.SqlServer.SqlServerCache.SetAsync(String key, Byte[] value, DistributedCacheEntryOptions options, CancellationToken token)
   at Microsoft.Identity.Web.TokenCacheProviders.Distributed.MsalDistributedTokenCacheAdapter.WriteCacheBytesAsync(String cacheKey, Byte[] bytes)
   at Microsoft.Identity.Web.TokenCacheProviders.MsalAbstractTokenCacheProvider.OnAfterAccessAsync(TokenCacheNotificationArgs args)
   at Microsoft.Identity.Client.TokenCache.Microsoft.Identity.Client.ITokenCacheInternal.OnAfterAccessAsync(TokenCacheNotificationArgs args)
   at Microsoft.Identity.Client.TokenCache.Microsoft.Identity.Client.ITokenCacheInternal.SaveTokenResponseAsync(AuthenticationRequestParameters requestParams, MsalTokenResponse response)
   at Microsoft.Identity.Client.Cache.CacheSessionManager.SaveTokenResponseAsync(MsalTokenResponse tokenResponse)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.CacheTokenResponseAndCreateAuthenticationResultAsync(MsalTokenResponse msalTokenResponse)
   at Microsoft.Identity.Client.Internal.Requests.ConfidentialAuthCodeRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenByAuthorizationCodeParameters authorizationCodeParameters, CancellationToken cancellationToken)
   at Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(AuthorizationCodeReceivedContext context, IEnumerable`1 scopes)
   at Microsoft.Identity.Web.WebAppServiceCollectionExtensions.<>c__DisplayClass4_1.<<AddWebAppCallsProtectedWebApi>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RunAuthorizationCodeReceivedEventAsync(OpenIdConnectMessage authorizationResponse, ClaimsPrincipal user, AuthenticationProperties properties, JwtSecurityToken jwt)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()
ClientConnectionId:4ff1d0a6-7a0f-49a9-97e3-f05353ed708e
Error Number:18456,State:1,Class:14
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\3.1.3\Microsoft.AspNetCore.Diagnostics.Abstractions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware: Error: An unhandled exception has occurred while executing the request.

System.Exception: An error was encountered while handling the remote login.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user ''.
   at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Extensions.Caching.SqlServer.DatabaseOperations.SetCacheItemAsync(String key, Byte[] value, DistributedCacheEntryOptions options, CancellationToken token)
   at Microsoft.Extensions.Caching.SqlServer.SqlServerCache.SetAsync(String key, Byte[] value, DistributedCacheEntryOptions options, CancellationToken token)
   at Microsoft.Identity.Web.TokenCacheProviders.Distributed.MsalDistributedTokenCacheAdapter.WriteCacheBytesAsync(String cacheKey, Byte[] bytes)
   at Microsoft.Identity.Web.TokenCacheProviders.MsalAbstractTokenCacheProvider.OnAfterAccessAsync(TokenCacheNotificationArgs args)
   at Microsoft.Identity.Client.TokenCache.Microsoft.Identity.Client.ITokenCacheInternal.OnAfterAccessAsync(TokenCacheNotificationArgs args)
   at Microsoft.Identity.Client.TokenCache.Microsoft.Identity.Client.ITokenCacheInternal.SaveTokenResponseAsync(AuthenticationRequestParameters requestParams, MsalTokenResponse response)
   at Microsoft.Identity.Client.Cache.CacheSessionManager.SaveTokenResponseAsync(MsalTokenResponse tokenResponse)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.CacheTokenResponseAndCreateAuthenticationResultAsync(MsalTokenResponse msalTokenResponse)
   at Microsoft.Identity.Client.Internal.Requests.ConfidentialAuthCodeRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenByAuthorizationCodeParameters authorizationCodeParameters, CancellationToken cancellationToken)
   at Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(AuthorizationCodeReceivedContext context, IEnumerable`1 scopes)
   at Microsoft.Identity.Web.WebAppServiceCollectionExtensions.<>c__DisplayClass4_1.<<AddWebAppCallsProtectedWebApi>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RunAuthorizationCodeReceivedEventAsync(OpenIdConnectMessage authorizationResponse, ClaimsPrincipal user, AuthenticationProperties properties, JwtSecurityToken jwt)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()
ClientConnectionId:4ff1d0a6-7a0f-49a9-97e3-f05353ed708e
Error Number:18456,State:1,Class:14
   --- 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.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
The thread 0x4c98 has exited with code 0 (0x0).
bgavrilMS commented 3 years ago

@jmprieur - could you or Jenny investigate this? Or does CXP handle token cache implementaions?

jmprieur commented 3 years ago

It's on my list @bgavrilMS. I was already monitoring it (see the label). I just did not get to it yet ... OOF

jmprieur commented 3 years ago

This is a SQL server connection error. You need to have the right connection string for your SQL database. This error has nothing to do with the sample. S See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization#distributed-token-cache on how to setup the connection string

Proposing to close this issue as external, but feel free to reopen if you disagree.