Basic authentication is base64 encoded and added to the HTTP Authorization header. See this SO post.
Api call through VS studio Console in c# fails
CzarR
296
Reputation points
HI, the Api call (Patch) through Visual Studio Console app is failing with the following error "The remote server returned an error: (403) Forbidden.". The same call works fine when I use Postman(Basic authentication with username and password). I get the response back from Postman. What could be the issue with the c# program. Please suggest. Thanks in advance. .NET framework 4.7.
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var result = string.Empty;
string json = @"{
""schemas"": [
""urn:scim:schemas:core:2.0:User"",
""urn:scim:schemas:extension:fa:2.0:faUser""
],
""userName"": ""ZMatt.Dandon @cmpy.com"",
""name"": {
""familyName"": ""Dandon"",
""givenName"": ""ZMatt""
},
""displayName"": ""ZMatt Dandon"",
""preferredLanguage"": ""en"",
""active"": false
}";
string url = @"https://url/hcmRestApi/scim/Users/C8FF94E381891376E050480A69294891";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
Req.Credentials = new NetworkCredential("UserName", "Password");
//Content_type
Req.ContentType = "application/vnd.oracle.adf.action+json";
//HTTP method
Req.Method = "PATCH";
using (var streamWriter = new StreamWriter(Req.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)Req.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
}
}
Accepted answer
2 additional answers
Sort by: Most helpful
-
P a u l 10,406 Reputation points
2021-09-13T22:17:59.867+00:00 Are "UserName" and "Password" your real credentials?
-
CzarR 296 Reputation points
2021-09-14T13:31:39.89+00:00 OK, @AgaveJoe that is correct. THank you so much for the answer.
Here is the updated code
// Making Web Request HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url); //Req.Credentials = new NetworkCredential("00OracleERPuser", "PMT12345"); string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8") .GetBytes("UserName" + ":" + "Password")); Req.Headers.Add("Authorization", "Basic " + encoded);