Search code examples
asp.net-coreopenid-connectthinktecture-ident-serverthinktectureasp.net-core-middleware

Configuring ASP.Net Core to authenticate using OIDC against Thinktecture V2


I'm trying to get an ASP.Net Core to authenticate against Thinktecture V2 uising OpenID Connect (we currently need WS-Trust so can't upgrade).

My configuration is as follows

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        certStore.Open(OpenFlags.ReadOnly);

        var cert = certStore.Certificates.Find(X509FindType.FindByThumbprint, "CertThumbprint", false);

        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            RequireHttpsMetadata = false,
            ClientId = _config["OpenID:ClientId"],
            ClientSecret = _config["OpenID:ClientSecret"],
            Authority = _config["OpenID:Authority"],
            ResponseType = OpenIdConnectResponseType.Code,
            PostLogoutRedirectUri = _config["OpenID:PostLogoutRedirectUri"],
            SignInScheme = "Cookies",
            CallbackPath = "/signin-oidc",
            TokenValidationParameters = new TokenValidationParameters()
            {
                IssuerSigningKey = new X509SecurityKey(cert[0]),                                 
            },
            Configuration = new OpenIdConnectConfiguration
            {

                Issuer = "https://identityserver/IdentityServer/issue",
                AuthorizationEndpoint = "https://identityserver/IdentityServer/issue/oidc/authorize",
                TokenEndpoint = "https://identityserver/IdentityServer/issue/oidc/token",
                UserInfoEndpoint = "https://identityserver/IdentityServer/issue/oidc/userinfo",

            }
        });

config.json

"OpenID": {
"ClientId": "Test",
"ClientSecret": "{6DD502AB-2AB1-4028-BD4A-85C91790EC7B}",
"Authority": "https://identityserver/IdentityServer/issue/oidc",
"PostLogoutRedirectUri": "https://localhost:44353/" }

When I try and authenticate I get the following exception:

HttpRequestException: Response status code does not indicate success: 400 (Bad Request).

The trace from thinktectureIdentityServer.svclog is

enter image description here

If anyone could provide any help it would be greatly appreciated.


Solution

  • I've got past the above error by handling the OnAuthorizationCodeReceivedEvent and manually handle the code redemption, in which I added a Basic Authorization header to authorise the client.

    new OpenIdConnectOptions
    {
        ...
    
        Events = new OpenIdConnectEvents
        {
           OnAuthorizationCodeReceived = async context =>
           {
               context.HandleCodeRedemption();
    
               var requestMessage = new HttpRequestMessage(HttpMethod.Post, context.Options.Configuration.TokenEndpoint);
    
               requestMessage.Content = new FormUrlEncodedContent(context.TokenEndpointRequest.Parameters);
    
               var authString = string.Format("{0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(_config["OpenID:ClientId"] + ":" + _config["OpenID:ClientSecret"])));
    
               requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
    
               var responseMessage = await context.Backchannel.SendAsync(requestMessage);
    
               responseMessage.EnsureSuccessStatusCode();
               var tokenResonse = await responseMessage.Content.ReadAsStringAsync();
               var jsonTokenResponse = JObject.Parse(tokenResonse);
               context.TokenEndpointResponse = new OpenIdConnectMessage(jsonTokenResponse);
           }
        }
    
        ...
    
    });
    

    To make the final call to retrieve the UserInfo I had to make changes the Identity Server to include a subject in the response that matches the subject in the Id Token. This involved updating the UserInfoController to add a claim in the Get method.