github Auth using RestRequest in github - c#

I am getting the error on request to a github.
"Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes"
This is my code:
var client = new RestClient
{
BaseUrl = "https://api.github.com",
Authenticator = new HttpBasicAuthenticator(_username, _password)
};
//client.AddDefaultHeader("User-Agent", "http://developer.github.com/v3/"+_username);
_restRequest = new RestRequest(Method.POST)
{
Resource = _resource,
RequestFormat = DataFormat.Json
};
// _restRequest.AddHeader("User-Agent",);
_restRequest.AddBody(new { title = form["feedbackmessage"], body = html, labels = new List<string> { _defaultlabel } });
_restRequest.AddHeader("User-Agent", "http://developer.github.com/v3/#" + _username);
var response = client.Execute(_restRequest);

According to GitHub Documentation, all API requests MUST include a valid User-Agent header.
What i have done was adding this User-Agent to my HttpClient like this:
_httpClient.DefaultRequestHeaders.Add("User-Agent", "Other");
and I did a normal request, for example:
var json = await HttpClient.GetStringAsync(url);
and it worked pretty well.
Another nice reference for it, you can check here.

I also faced with similar issue today. As far as I understood from GitHub doc, it doesn't have to be URL-like style, like in your example. Having just _username as User-Agent value is enough.
It didn't work for me with _restRequest.AddHeader("User-Agent"... as well and started working only after adding:
client.UserAgent = _username;
or
var client = new RestClient
{
BaseUrl = "https://api.github.com",
Authenticator = new HttpBasicAuthenticator(_username, _password),
UserAgent = _username
};

Related

How to add bearertoken to post/get restsharp automation testing

maybe anyone could help me with RestSharp api automation testing.
I'll try to be as clear as possible.
Basically the scheme is:
I'm sending my username/password credentials & I get BearerToken in return.
I parse the bearer token into a json file.
After I get the bearer token I need to "Authenticate" in order to get the information that I need.
For example i need full company credit report which I get after I input companyName ="Whatever"; companyCode = "Whatever";
{
var client = new RestClient("https://www.myapitesting.com/api/Auth/Authenticate");
var request = new RestRequest(Method.GET);
var body = new AuthenticatePostCredentials { Username = "myUserName", Password = "myPassword" };
request.AddJsonBody(body);
var response = client.Post(request);
HttpStatusCode statusCode = response.StatusCode;
int numericStatusCode = (int)statusCode;
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<object>(request).Data;
string jsonToken = JsonConvert.SerializeObject(queryResult);
var JSON1 = JToken.Parse(jsonToken);
var pureToken = JSON1.Value<string>("token");
File.WriteAllText(#"C:\Users\....\TestAPI\TestAPI\token.json", pureToken);
Console.WriteLine(pureToken);
Console.WriteLine(numericStatusCode)
The output I get is: token, status code 200 (correct credentials to get the bearertoken)
//////////At this point I get the token and it is writed into my json file/////////////// (the token works)
Now im trying to authenticate with my token and get the company information that I need
var client = new RestClient("https://www.myapitesting.com/api/GetCompanyReport");
var myRequest = new RestRequest(Method.POST);
myRequest.AddHeader("Accept", "application/json");
myRequest.AddHeader("Authorization", $"Bearer{pureToken}");
myRequest.AddHeader("content-type", "application/json");
var companyInfoInput = new AuthenticatePostCredentials { companyName = "MyCompanyName", companyCode = "MyCompanyCode" };
requestas.AddJsonBody(companyInfoInput);
var response = myRequest.Execute(request);
Console.WriteLine(response.Content);
The output I get is error code that says I havent authenticated, even though I pass the bearer token with my addHeader command.
{"ErrorId":401,"ErrorName":"Unauthorized","ErrorDescription":"User is not logged in"}
What am I doing wrong? Any kind of help would be greatly appreciated!
In this case, you could load the "Authenticator" you want to use, in the case of JWT you may instantiate something like this:
var authenticator = new JwtAuthenticator(pureToken);
and then set your client authenticator like this:
client.Authenticator = authenticator;
Mainly, you should not need to set headers by hand for the most commons ones using Restsharp.
You can for example fix this statement:
var myRequest = new RestRequest(url, DataFormat.Json);
var response = client.Post(request);
I also made this gist for you to check an example
If you want to see something more complete I also have this another gist

Microsoft Graph Post action to Create group "Bad request"

We are trying to POST a request to the Microsoft Graph API to create a group, like explained HERE
The base url is: https://graph.microsoft.com/v1.0/groups
Content type is set to apllication/json
We have a valid Baerer token as well.
We are using the Group class from the Microsoft.Graph namespace (NuGet Package) so we populate the properties with our data and call the JsonConvert.SerializeObject(group) to serialize the group objecet to Json.
This is how we build up and serialze:
Microsoft.Graph.Group group = new Microsoft.Graph.Group();
group.Description = "Self help community for library";
group.DisplayName = "Library Assist";
group.GroupTypes = new[] { "Unified" };
group.MailEnabled = true;
group.MailNickname = "library";
group.SecurityEnabled = true;
string json = JsonConvert.SerializeObject(group);
var content = new StringContent(json);
var response = httpclient.PostAsJsonAsync(Uri, content).Result;
The headers of the HttpClient are set like this:
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "...value of baerer token...");
httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
We are building the URL up starting from https://graph.microsoft.com/v1.0
adding /groups to it
In the response we are getting a Bad request status code 400.
This is implying that there is an error in the request URI, headers, or body but in the Graph Explorer the same code as above works fine, we get results in the response.
What am i overseeing?
Thank you for any feedback or suggestion.
Kind regards.
Since you already using the Microsoft.Graph namespace, you can use built-in the GraphServiceClient to make request as below. You needn't use the http client or serialize objects, this will be handled :
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", "<your-access-token>");
}));
var group = new Microsoft.Graph.Group
{
DisplayName = "Library Assist",
Description = "Self help community for library",
MailNickname = "library",
MailEnabled = true,
SecurityEnabled = true,
GroupTypes = new List<string> { "Unified" }
};
var createdGroup = await graphserviceClient.Groups.Request().AddAsync(group);
Reference - Intro to the Microsoft Graph .NET Client Library

How do we call GitLab API from c# application?

How do we call GitLab API using access token to get all the commits in a project.
I am getting unauthorized error.
string Url = "http://xxxxxx/DevOps/WebApp1.git/repository/commits";
using(var client = new WebClient()) //WebClient
{
client.BaseAddress = Url;
//client.UseDefaultCredentials = true;
client.Headers.Add("Content-Type:application/json"); //Content-Type
client.Headers.Add("Accept:application/json");
client.Headers[HttpRequestHeader.Authorization] = "Bearer xxxxx";
var commits_List = client.DownloadString(Url);
}
The documentation clearly states:
You can use a personal access token to authenticate with the API by passing it in either the private_token parameter or the Private-Token header.
You are doing neither of them.
Remove your authorization header and replace it with this:
client.Headers["Private-Token"] = "xxxxx";
Try:
https://gitlab.com/api/v4/projects/{your_project_id}/repository/commits?private_token={your_private_token}

Dropbox Request URL path to file C#

I have OneDrive & Google Drive successfully processing chunked download however Dropbox is giving me grief because I cannot get the correct http request path to the file.
I am not an expert in rest url's & endpoints, maybe someone can point me in the right direction for the acceptable dropbox request format for the latest UWP SDK.
using (var httpRequest = new HttpRequestMessage())
{
string url = "https://content.dropboxapi.com/1/files/auto" + uri;
string accessKey = ApplicationData.Current.LocalSettings.Values[CommonData.dropboxAccessToken_Key].ToString();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessKey);
}
I have read docs on Dropbox and it is not clear on the formatting for me, also I could not find a clear example anywhere.
Thanks again!
According to your code, the problem here is in your authorization header. For Dropbox API, the correct authorization header should like following:
Authorization: Bearer <access token>
So we should change httpRequest.Headers.Authorization to
httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
Then your code should be albe to work. Using "file.mp3" under "temp" folder for example.
The code may like:
var uri = "/temp/file.mp3";
using (var httpClient = new HttpClient())
{
using (var httpRequest = new HttpRequestMessage())
{
string url = "https://content.dropboxapi.com/1/files/auto" + Uri.EscapeDataString(uri);
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.SendAsync(httpRequest);
if (response.IsSuccessStatusCode)
{
//TODO
}
}
}

Https client with authorization in C#

I'm trying to create a https client in C#.
I had HTTP client which worked fine and I changed it to work with HTTPS. But unfortunately there is something wrong with the authorization (the server uses OAuth 2).
My program sends a request to a server and gets the token. But it can't get or send any data from the server.
The server works fine with other clients, so it's not its fault.
This is a piece of code which causes the problem. I know that, because when I comment authorization on the server, the data is send (everything is fine).
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
This is the whole function, which should send data:
WebRequestHandler handler = new WebRequestHandler();
X509Certificate certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
var client = new HttpClient(handler);
string uri = "https://192.168.0.10:8443/data";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("Authorization: {0}", token))));
client.BaseAddress = new Uri(uri);
var parameters = new Dictionary<string, string>();
parameters["name"] = name;
parameters["surname"] = surname;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(parameters);
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var response = client.PostAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
Console.WriteLine((response.StatusCode.ToString()));
string resultContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
I guess I'm missing something in the header but can't find any information in the documentation about that.
It's a difficult issue so any advice will be very appreciated.
You shouldn't be including the HTTP header name ("Authorization: ") in the parameter of the AuthenticationHeaderValue. Setting the Authorization property will add the header to the request.
Additionally for OAuth 2, you probably want to be using "Bearer" as the scheme and not encoding token with base64.
Something like this should therefore work:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

Categories

Resources