Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in database connection duende development testing #508

Closed
Bayah97 opened this issue Feb 13, 2023 · 12 comments
Closed

Error in database connection duende development testing #508

Bayah97 opened this issue Feb 13, 2023 · 12 comments

Comments

@Bayah97
Copy link

Bayah97 commented Feb 13, 2023

Which version of Duende BFF are you using?
Duende IdentityServer version 6.2.1+bda14c367eb8a85f3dae614fa0ac1005bb13dfdc

Which version of .NET are you using?
(.NET 6.0.12)

Question
Im receiving error cannot connect with database on first run in development testing ? After i logout and login again, there are no problem. Is it because i dont have valid license ?

@Bayah97 Bayah97 added the BFF label Feb 13, 2023
@brockallen
Copy link
Member

Im receiving error cannot connect with database on first run in development testing

Do you have any more details?

Is it because i dont have valid license ?

No. Invalid license errors are simply surfaced as entries in the logging system: https://docs.duendesoftware.com/identityserver/v6/fundamentals/license_key/#license-validation-and-logging

@brockallen
Copy link
Member

Any updates here?

@Bayah97
Copy link
Author

Bayah97 commented Feb 17, 2023

Hi,

I am using seriLog for Duende Identity Server. I found repeating error but in different places. When i run for first time, the error after GET connect/authorize. I stop and run again the identity server, the same error after found bearer token. But after GET connect/authorize log, no error like the first run.

The error Log is:
at Duende.IdentityServer.EntityFramework.Stores.ClientStore.FindClientByIdAsync(String clientId) in /_/src/EntityFramework.Storage/Stores/ClientStore.cs:line 78

@brockallen
Copy link
Member

The error Log is:
at Duende.IdentityServer.EntityFramework.Stores.ClientStore.FindClientByIdAsync(String clientId) in /_/src/EntityFramework.Storage/Stores/ClientStore.cs:line 78

Is there more info here from the logs? I can't tell from this alone what the problem might be.

@Bayah97
Copy link
Author

Bayah97 commented Feb 18, 2023

Hi

This is my code for identity server:

public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
{
builder.Services.AddRazorPages();

    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(connectionString));

    builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    builder.Services.AddIdentityServer(options =>
        {
            //to show events in serilog
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;

            //include an audience claim in the issued tokens
            options.EmitStaticAudienceClaim = true;

            //use key management to secure communication(Signing key)
            options.KeyManagement.Enabled = true;

            //digital signatures generated
            options.KeyManagement.SigningAlgorithms = new[]
            {
                // RS256 for older clients (with additional X.509 wrapping)
                new SigningAlgorithmOptions(SecurityAlgorithms.RsaSha256) { UseX509Certificate = true },
            };
        })
        .AddConfigurationStore(options =>
        {
            options.ConfigureDbContext = b => b.UseSqlServer(connectionString);
        })
        .AddOperationalStore(options =>
        {
            options.ConfigureDbContext = b => b.UseSqlServer(connectionString);
        })
        .AddAspNetIdentity<ApplicationUser>();

    builder.Services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyHeader()
        .AllowAnyOrigin()
        .AllowAnyMethod());
    });

        return builder.Build();
 }

public static WebApplication ConfigurePipeline(this WebApplication app)
{
app.UseSerilogRequestLogging();

    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseCors("CorsPolicy");
    }

    /*InitializeDatabase(app);
    EnsureSeedData(app);*/        

    app.UseStaticFiles();
    app.UseRouting();
        
    app.UseIdentityServer();

    app.UseAuthorization();
    app.MapRazorPages().RequireAuthorization();

    return app;
}

@brockallen
Copy link
Member

Is there more info here from the logs? I can't tell from this alone what the problem might be.

We need error logs, I think. They should contain the message as to the problem.

@Bayah97
Copy link
Author

Bayah97 commented Feb 21, 2023

The video link:

https://drive.google.com/file/d/1l0-vakjvRtdnmRbhRJNjrLEUvuN2cm8F/view?usp=sharing

Issue:
PersistedGrant table insert 2 row refresh token only on first time run server. After LogOut and Login again, only one row inserted. The error for database connection only show on the first run only.

Here the error log:
[11:15:23 Error] Microsoft.EntityFrameworkCore.Database.Connection
An error occurred using the connection to database 'DuendeServer2' on server 'BGAUTMSABARIAH'.

[11:15:23 Error] Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware
An unhandled exception has occurred while executing the request.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SplitQueryingEnumerable1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.SplitQueryingEnumerable1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable1 source, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToArrayAsync[TSource](IQueryable1 source, CancellationToken cancellationToken) at Duende.IdentityServer.EntityFramework.Stores.ClientStore.FindClientByIdAsync(String clientId) in /_/src/EntityFramework.Storage/Stores/ClientStore.cs:line 78 at Duende.IdentityServer.Stores.ValidatingClientStore1.FindClientByIdAsync(String clientId) in //src/IdentityServer/Stores/ValidatingClientStore.cs:line 54
at Duende.IdentityServer.Stores.IClientStoreExtensions.FindEnabledClientByIdAsync(IClientStore store, String clientId) in /
/src/IdentityServer/Extensions/IClientStoreExtensions.cs:line 23
at Duende.IdentityServer.Validation.TokenValidator.ValidateJwtAsync(String jwtString, IEnumerable1 validationKeys, Boolean validateLifetime, String audience) in /_/src/IdentityServer/Validation/Default/TokenValidator.cs:line 335 at Duende.IdentityServer.Validation.TokenValidator.ValidateAccessTokenAsync(String token, String expectedScope) in /_/src/IdentityServer/Validation/Default/TokenValidator.cs:line 154 at Duende.IdentityServer.Validation.UserInfoRequestValidator.ValidateRequestAsync(String accessToken) in /_/src/IdentityServer/Validation/Default/UserInfoRequestValidator.cs:line 52 at Duende.IdentityServer.Endpoints.UserInfoEndpoint.ProcessUserInfoRequestAsync(HttpContext context) in /_/src/IdentityServer/Endpoints/UserInfoEndpoint.cs:line 81 at Duende.IdentityServer.Endpoints.UserInfoEndpoint.ProcessAsync(HttpContext context) in /_/src/IdentityServer/Endpoints/UserInfoEndpoint.cs:line 62 at Duende.IdentityServer.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IdentityServerOptions options, IEndpointRouter router, IUserSession userSession, IEventService events, IIssuerNameService issuerNameService, ISessionCoordinationService sessionCoordinationService) in /_/src/IdentityServer/Hosting/IdentityServerMiddleware.cs:line 101 at Duende.IdentityServer.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes) in /_/src/IdentityServer/Hosting/MutualTlsEndpointMiddleware.cs:line 94 at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Duende.IdentityServer.Hosting.DynamicProviders.DynamicSchemeAuthenticationMiddleware.Invoke(HttpContext context) in /_/src/IdentityServer/Hosting/DynamicProviders/DynamicSchemes/DynamicSchemeAuthenticationMiddleware.cs:line 47 at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>g__InvokeCoreAwaited|15_0(HttpContext context, Task1 policyTask)
at Duende.IdentityServer.Hosting.BaseUrlMiddleware.Invoke(HttpContext context) in /_/src/IdentityServer/Hosting/BaseUrlMiddleware.cs:line 27
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

@brockallen
Copy link
Member

System.Threading.Tasks.TaskCanceledException: A task was canceled.

Ok, this is the exception. You can ignore this, as it's related to all of this: DuendeSoftware/IdentityServer#1084

and this: DuendeSoftware/IdentityServer#1040

The filter we added in the PR can help, so I'd suggest updating to that version (6.2.0).

@Bayah97
Copy link
Author

Bayah97 commented Feb 22, 2023

My duende version is this:
Duende IdentityServer version 6.2.1

Do i need to downgrade it to 6.2.0 ?
and will this solve the issue of multiple insert data in database ?

@brockallen
Copy link
Member

My duende version is this: Duende IdentityServer version 6.2.1

Oh I'm sorry -- I misread it from above. You should be on the correct version that filters the exceptions.

So looking more at your call stack, it looks like the DeveloperExceptionPageMiddleware is catching it and logging (and maybe re-throwing the exception). In short, this is something you should catch and decide if you allow it to be logged and/or re-thrown. Also, do you enable DeveloperExceptionPageMiddleware in production? If not, then maybe this is something you only see at dev time.

This scenario is caused by the browser closing the connection, which is not really a bug and also not something you can really do much about. Just manage it the best you can in the way you want to.

@josephdecock
Copy link
Member

Any further update here? Can we close this issue?

@Bayah97
Copy link
Author

Bayah97 commented Mar 1, 2023

Yup, Thank you @brockallen

@Bayah97 Bayah97 closed this as completed Mar 1, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants