How to write Python b"mystring" in C# - c#

Short Story:
I tried
Encoding.ASCII.GetBytes("mystring")
but it seems not to be working...
Long Story:
I am trying to call an API and I have this python sample code available:
userpass = username + ":" + password
encoded_credentials = b"Basic " + base64.b64encode(userpass.encode('ascii'))
headers = {'Version': '2.0', 'Accept': 'application/json', 'Authorization': encoded_credentials}
url = 'https://' + server_ip + '/api/help/capabilities'
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
The c# code I made is:
string userpass = username + ":" + password;
byte[] encodedbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(userpass);
var encoded_credentials = Encoding.ASCII.GetBytes("Basic ") + Convert.ToBase64String(encodedbytes);
var request = (HttpWebRequest)WebRequest.Create("https://" + server_ip + "/api/help/capabilities");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", encoded_credentials);
var response = (HttpWebResponse)request.GetResponse()
And the result I get is 401, unauthorized... so I believe I miss something in the encoding procedure of the username-password!

var encoded_credentials = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userpass));
That is the answer to my "Long Story" question!
I managed to figure out after debugging the python code (that did authorize), so I took the encoded_credentials and used it in my c# code, so it successfully authorized too...
Then I compared the faulty value to the correct and with a couple of tries, I ended up with the correct one!
This leads me to the conclusion that the correct answer to the "Short Story" question is just:
"mystring"

Related

How to request an access token from OAuth using System.Net.Http? 401 Error

Context
I am developing a simple application that requires to receive List Data from a company Online SharePoint site. In order to make REST requests, I must first retrieve an access token from Microsoft's access control service. Despite attempting some tutorials and reading documentation, I am new to REST/HTTP am am failing to do so.
What have I tried?
Used SharePoint appregnew.aspx to register my app, and generate "Client ID" and "Client Secret" values. https://[sitename].sharepoint.com/_layouts/15/appregnew.aspx
Used Sharepoint appinv.aspx to authorize my app with read control and generate a "Tenant ID".
https://[sitename].sharepoint.com/_layouts/15/appinv.aspx
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read"/>
</AppPermissionRequests>
Used SharePoint AppPrincipals.aspx to verify Tenant ID. https://[sitename].sharepoint.com/_layouts/15/AppPrincipals.aspx
Attempted several methods of formatting the request with the following being the latest:
Updated
// Variables removed for security
class Program
{
static void Main(string[] args)
{
WebRequest myWebRequest;
string stGetAccessTokenUrl = "https://accounts.accesscontrol.windows.net/{0}/tokens/OAuth/2";
string tenantID = "myTenantID";
string resourceID = "00000003-0000-0ff1-ce00-000000000000";
string stClientID = "myClientID";
string stClientSecret = "myClientSecret";
string stSiteDomain = "[myCompany].sharepoint.com";
// URL Format
stGetAccessTokenUrl = string.Format(stGetAccessTokenUrl, tenantID);
myWebRequest = WebRequest.Create(stGetAccessTokenUrl);
myWebRequest.ContentType = "application/x-www-form-urlencoded";
myWebRequest.Method = "POST";
// Add the below body attributes to the request
var postData = "grant_type=client_credentials";
postData += "&client_id=" + stClientID + "#" + tenantID;
postData += "&client_secret=" + stClientSecret;
postData += "&resource=" + resourceID + "/" + stSiteDomain + "#" + tenantID;
var data = Encoding.ASCII.GetBytes(postData);
using (var stream = myWebRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)myWebRequest.GetResponse();
}
}
What doesn't work?
I receive a 401 Unauthorized error despite the app having been assigned permissions.
Any help would be greatly appreciated!
Apologies, I forgot to return to this question upon resolving the issue. Credit to "Michael Han" within the comments of his own answer.
Answer
By default, the SharePoint app-only permissions is disabled for the tenant. A tenant administrator must first run the following cmdlet in PowerShell:
Set-SPOTenant -DisableCustomAppAuthentication $false
This parameter supersedes all other privilege settings and must first be configured.
You could refer to this article to get the access token : https://social.technet.microsoft.com/wiki/contents/articles/51982.sharepoint-read-online-list-data-from-c-console-application-using-access-token.aspx
#region Get Access Token using TenantID and App secret ID & Password
// URL Format
//https://accounts.accesscontrol.windows.net/tenant_ID/tokens/OAuth/2 Jump
stGetAccessTokenUrl = string.Format(stGetAccessTokenUrl, tenantID);
myWebRequest = WebRequest.Create(stGetAccessTokenUrl);
myWebRequest.ContentType = "application/x-www-form-urlencoded";
myWebRequest.Method = "POST";
// Add the below body attributes to the request
/*
* grant_type client_credentials client_credentials
client_id ClientID#TenantID
client_secret ClientSecret
resource resource/SiteDomain#TenantID resourceid/abc.sharepoint.com#tenantID
*/
var postData = "grant_type=client_credentials";
postData += "&client_id=" + stClientID +"#" +tenantID;
postData += "&client_secret=" + stClientSecret;
postData += "&resource=" + resourceID + "/" + stSiteDomain + "#" + tenantID;
var data = Encoding.ASCII.GetBytes(postData);
using (var stream = myWebRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)myWebRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
string[] stArrResponse = responseString.Split(',');
//get the access token and expiry time ,etc
foreach(var stValues in stArrResponse)
{
if(stValues.StartsWith("\"access_token\":"))
{
//Console.WriteLine(" Result => " + stValues);
accessToken = stValues.Substring(16);
//Console.WriteLine(" Result => " + accessToken);
accessToken = accessToken.Substring(0,accessToken.Length-2);
// Console.WriteLine(" Result => " + accessToken);
}
}

google api call to big query wont give refresh token using c#

I have read and read and played with this code inside out and I still cant work out how to get the refresh token. This in c#
I have tried different combo of access_type, prompt and approval_prompt params.
I keep revoking access by my user to the app, so when the auth code is being requested it does ask for myself to approve the app to be able to access.
I just want to get the refresh token so i can store it and keep refreshing.
here is the code below. I have removed the parts to get the auth code, but if it is needed i can add in. I wonder if anyone can simply spot something simply wrong.
string GetJsonFromAPICall(string p_url,string p_post_data, string p_b64_id_secret)
{
//string C_TOKEN_URL = "https://oauth2.googleapis.com/token";
string l_auth_string = "Basic " + p_b64_id_secret;
print("p_post_data = ", p_url + "?"+p_post_data);
print("Authorization", l_auth_string);
HttpWebRequest request = WebRequest.Create(p_url) as HttpWebRequest;
string postData = p_post_data;// "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
request.Headers.Add("Authorization", l_auth_string);
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
print("pos 20 in GetJsonFromAPICall");
print("length ", data.Length.ToString());
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
string getAccessToken(string p_b64_id_secret, string p_auth_code, string p_redirect_url)
{
//string l_url = "client_id="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_ID + "&client_secret="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_SECRET + "access_type=offline&prompt=consent&grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
string l_params = "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
l_params += "&access_type=offline";
l_params += "&prompt=consent";
l_params += "&approval_prompt=force";
//return GetJsonFromAPICall("https://oauth2.googleapis.com/token", l_params, p_b64_id_secret);
return GetJsonFromAPICall("https://www.googleapis.com/oauth2/v4/token", l_params, p_b64_id_secret);
}
var credentials = string.Format("{0}:{1}", C_GBQ_ONLINE_APP_APP_CLIENT_ID, C_GBQ_ONLINE_APP_APP_CLIENT_SECRET_ID);
var b64_id_secret = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
string l_auth_code = "xxxxx"; // worked out successfully earlier
l_json_returned = getAccessToken(p_b64_id_secret, l_auth_code, C_GBQ_ONLINE_APP_REDIRECT_URL);
the returned json is
l_json_returned = : {
"access_token": "FFFFFFFF",
"expires_in": 3569,
"scope": "https://www.googleapis.com/auth/cloud-platform.read-only https://www.googleapis.com/auth/bigquery",
"token_type": "Bearer"
}

C# does not receive any response values from Jenkins

I'm calling Jenkins jobs from C# using the WebClient class and I'm not receiving any response even though the Jenkins job is triggering and executing properly. I need to read the headers to get the queue number and things like that, so I'm confused as to why this is happening. Below is my code, which works just fine except for "response" is always an empty string; not null, just an empty string:'
'
using (var wb = new WebClient())
{
string url = "http://url:8080/job/CloudTeam/job/Azure/job/Create-Azure-VM/buildWithParameters";
string queryString = "HOSTNAME=" + virtualMachine.Hostname + "&IPADDRESS=" + virtualMachine.IPAddress + "&RESOURCEGROUP=" + virtualMachine.ResourceGroup + "&STORAGEACCOUNT=" + virtualMachine.StorageAccount + "&BASEIMAGE=" + virtualMachine.BaseImage;
string password = "password";
string username = "user";
string basicAuthToken = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
wb.Headers["Authorization"] = "Basic " + basicAuthToken;
wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wb.Headers.Add("user", "user:password");
string response = wb.UploadString(url, queryString);
return response; <-- always an empty string
}
'

One drive Rest api server bad request 400 when uploading file

this my code for create session and upload file in onedrive
string url = "https://api.onedrive.com/v1.0/drive/root:/" + "Nopbackup" +":/" + "" + fileName +":/upload.createSession" + "";
var result = string.Empty;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/json";
request.ContentType = "contentType";
//request.ac = "application/json";
request.Headers.Add("Authorization", tokenType + " " + accessToken);
request.ContentLength = 0;
//byte[] requestData = Encoding.UTF8.GetBytes(url);
//using (Stream st = request.GetRequestStream())
// st.Write(requestData, 0, requestData.Length);
WebResponse response = request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
result = streamReader.ReadToEnd();
its giving server bad request 400 error
I think the issue is the URL you're POSTing with. It looks like this:
string url = "https://api.onedrive.com/v1.0/drive/root:/" + "Nopbackup" +":/" + "" + fileName +":/upload.createSession" + "";
Which turns out to be
https://api.onedrive.com/v1.0/drive/root:/Nopbackup:/filename:/upload.createSession
You've got the colon syntax a little messed up, and the API doesn't know what to do with that (hence the bad request).
Try building the URL like this instead:
string url = "https://api.onedrive.com/v1.0/drive/root:/" + "Nopbackup" + "/" + fileName +":/upload.createSession";
And I think things will work better for you.

TeamCity - Unable to authenticate via API

I've been struggling with authentication in TeamCity through the API lately. I can access the resources directly in my browser (http://usr:pw#teamcity:8111/httpAuth/app/rest/...), but doing so programmatically returns 401-Unauthorized.
WebRequest request = WebRequest.Create("http://user:pwd#teamcity:8111/httpAuth/app/rest/projects");
request.Method = WebRequestMethods.Http.Get;
try
{
request.Timeout = Timeout.Infinite;
WebResponse response = request.GetResponse(); //Returns 401:Unauthorized
I can use guestAuth(http://teamcity:8111/guestAuth/app/rest/projects) without any problem, so there should not be any problem with the WebRequest itself.
Does anyone have an idea?
Try to add your credentials and then make request.it will be get what you need.
var username = "abc";
var password = "123";
var encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);

Categories