400 Bad Request HttpClient Mtls Certificate C#

Viewed 77

Im receiving 400 bad request from the endPoint. I can see the cert loaded in httpClientHandler and then in httpclient, but it doest work.

public HttpClientHandler generateCert() {

        var SignatureCertificateThumbprint = "8f375e9024722edca43913dc267956b00ed36f2b";
        X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);

        string certThumb = SignatureCertificateThumbprint.ToUpperInvariant();
        store.Open(OpenFlags.ReadOnly);
        IEnumerable<X509Certificate2> certificates = store.Certificates.OfType<X509Certificate2>();
        X509Certificate currentCert = certificates.FirstOrDefault(x => x.Thumbprint == certThumb);

        HttpClientHandler httpClientHandler = new HttpClientHandler();
        httpClientHandler.ClientCertificates.Add(currentCert);
        httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
        httpClientHandler.ServerCertificateCustomValidationCallback = (a, b, c, d) => { return true; };
        store.Close();
        
        return httpClientHandler;
    }

   


    public async Task<object> PostEndPoint(object dataObject, string url)
    {
        EndPointBearerTokenResponse onAuth = (EndPointBearerTokenResponse)GetAuthorizeToken().Result;
        var json = JsonConvert.SerializeObject(dataObject);
        StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

        ServicePointManager.Expect100Continue = true;
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };

        HttpClient client = new HttpClient(generateCert());
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue() { NoCache = true };
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", onAuth.access_token);

        var response = await client.PostAsync(url, data);}

I can use the endPoint from PostMan but not from app. Tnx for help. Regards

1 Answers

I had to add the private key into the cert generating a new file with both .cert and .key

Related