# Keycloak Jwt Validation with C#

**URL:** <https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047>\
**Category:** Securing applications\
**Created:** [October 23, 2023, 10:34am UTC](https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047 "2023-10-23T10:34:34Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Merlin](https://avatars.discourse-cdn.com/v4/letter/m/8baadc/32.png) [@Merlin](https://forum.keycloak.org/u/Merlin)\
**Post date:** [October 23, 2023, 10:34am UTC](https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047/1 "2023-10-23T10:34:34Z")

</div>

Hello together,

we want to validate a jwt we receive from keycloak in C# using openid connect.

We have this code:

```auto
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "http://localhost:8080";
        options.Audience = "my_client";
        options.RequireHttpsMetadata = false;
        options.MetadataAddress = "http://localhost:8080/realms/my_realm/.well-known/openid-configuration";

        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";

                // Customize the error response
                var message = "Authentication failed: " + context.Exception.Message;
                var errorResponse = JsonSerializer.Serialize(new { message });
                return context.Response.WriteAsync(errorResponse);
            }
        };
    });

```

And we receive this error message:

```auto
Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HMUJNLSECPBD", Request id "0HMUJNLSECPBD:00000001": An unhandled exception was thrown by the application.
      System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://localhost:8080/realms/my_realm/.well-known/openid-configuration'.
       ---> System.TypeLoadException: Could not load type 'Microsoft.IdentityModel.Json.JsonConvert' from assembly 'Microsoft.IdentityModel.Tokens, Version=7.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
         at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
         at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
         at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
         at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.Microsoft.IdentityModel.Protocols.IConfigurationRetriever<Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration>.GetConfigurationAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
         at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
         --- End of inner exception stack trace ---
         at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
         at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
         at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
         at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
         at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
         at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext context)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

```

Is there any configuration in keycloak we are missing or must we add something to our c# code?

Thank you for your help  
Merlin

---

<div class="post-metadata">

**Author:** ![mbonn](https://yyz2.discourse-cdn.com/free1/user_avatar/forum.keycloak.org/mbonn/32/5755_2.png) [@mbonn](https://forum.keycloak.org/u/mbonn)\
**Post date:** [October 23, 2023, 2:27pm UTC](https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047/2 "2023-10-23T14:27:36Z")

</div>

Have you checked that `http://localhost:8080/realms/my_realm/.well-known/openid-configuration` responds with a valid JSON-formatted configuration?

And I would try to configure the .NET’s `JwtBearerOptions.Authority` with the correct issuer:

```auto
options.Authority = "http://localhost:8080/realms/my_realm";

```

---

<div class="post-metadata">

**Author:** ![Merlin](https://avatars.discourse-cdn.com/v4/letter/m/8baadc/32.png) [@Merlin](https://forum.keycloak.org/u/Merlin)\
**Post date:** [October 23, 2023, 3:00pm UTC](https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047/3 "2023-10-23T15:00:17Z")

</div>

Thank you for your help, we fixed the issue. Some packages had a version missmatch.

---

<div class="post-metadata">

**Author:** ![mbogliacino](https://yyz2.discourse-cdn.com/free1/user_avatar/forum.keycloak.org/mbogliacino/32/9236_2.png) [@mbogliacino](https://forum.keycloak.org/u/mbogliacino)\
**Post date:** [November 6, 2023, 3:54pm UTC](https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047/4 "2023-11-06T15:54:34Z")

</div>

Hi!,  
I have same problem. Which of packages had been causing the problem?

---

<div class="post-metadata">

**Author:** ![Merlin](https://avatars.discourse-cdn.com/v4/letter/m/8baadc/32.png) [@Merlin](https://forum.keycloak.org/u/Merlin)\
**Post date:** [November 7, 2023, 8:13am UTC](https://forum.keycloak.org/t/keycloak-jwt-validation-with-c/23047/5 "2023-11-07T08:13:09Z")

</div>

Hi,  
the  
AspNetCore.Authentication.JWTBearer,  
AspNetCore.Authentication.OpenIdConnect,  
IdentityModel.JsonWebToken,  
IdentityModel.Protocols,  
IdentityModel.Protocols.OpenIdConnet and  
IdentityModel.Tokens.  
We set them all to 7.0.0
