0

I need an example of accessing an external API using OpenID Connect/OAuth authentication/authorization, and The supported OAuth flow is Authorization Code Flow with PKCE. endpoints use REST technology over HTTPS I know that I have to get the authorization code first, then ask for the authentication token. They have the OpenID Connect in this URL:https://iam.efatura.cv/auth/realms/taxpayers/.well-known/openid-configuration. I'm using C# winForm

I'm doing this and giving error 401.

try {

            string url5 = "https://iam.efatura.cv/auth/realms/taxpayers/protocol/openid-connect/token";
            string client_id = "";

            string client_secret = "";           

           
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url5);
            webRequest.PreAuthenticate = false;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Accept = "multipart/form-data";
            webRequest.Headers.Add("Authorization:" + Authorization(client_id, client_secret));
            var request = "grant_type=client_credentials";
            byte[] req_bytes = Encoding.ASCII.GetBytes(request);
            webRequest.ContentLength = req_bytes.Length;

            Stream strm = webRequest.GetRequestStream();
            strm.Write(req_bytes, 0, req_bytes.Length);
            strm.Close();

            MessageBox.Show(webRequest.Headers.ToString());
            HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
         

            String json = "";
            using (Stream respStr = resp.GetResponseStream())
            {
                using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8))
                {
                    //should get back a string i can then turn to json and parse for accesstoken
                    json = rdr.ReadToEnd();
                    rdr.Close();
                }
            }

           

        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
mason
  • 31,774
  • 10
  • 77
  • 121
carlosp
  • 1
  • 1
  • Why are you using WebRequest and so much code? In .NET Core HttpWebRequest is just a legacy wrapper over HttpClient. HttpClient itself is faster and easier to use even in .NET Framework. Almost all of this code would be replaced with 4-5 lines [as this answer shows](https://stackoverflow.com/a/20005964/134204). On top of that, HttpClient is thread-safe and meant to be reused. You could configure it just once, store it in a field and reuse it from multiple threads and methods – Panagiotis Kanavos Apr 06 '22 at 14:37
  • As for ` Encoding.ASCII.GetBytes(request)`, that's a bug. `Encoding.ASCII` refers to the 7-bit US-ASCII. All web sites and APIs use UTF8, including StackOverflow – Panagiotis Kanavos Apr 06 '22 at 14:39

0 Answers0