Closed multco-malan closed 2 years ago
Hi @multco-malan
Is this error happening locally(using a local SQL db) or just when you deploy it?
@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.
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.
@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
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.
@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).
@jmprieur - could you or Jenny investigate this? Or does CXP handle token cache implementaions?
It's on my list @bgavrilMS. I was already monitoring it (see the label). I just did not get to it yet ... OOF
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.
This issue is for a: (mark with an
x
)The issue was found for the following scenario:
Please add an 'x' for the scenario(s) where you found an issue
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:
Here is stack trace:
OS and Version?
Versions