I can get an access token of Office 365. I can not make a REST request (GET) attaching this token in the header.
I'm using this code:
RestClient client = new RestClient();
client.EndPoint = #"https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$top=10";
client.Method = HttpVerb.GET;
client.ContentType = "application/json";
client.PostData = "authorization: Bearer " + myAccesToken.ToString();
String json = client.MakeRequest();
I've tested the access token in http://jwt.calebb.net and it's ok.
But it's always returning:
The remote server returned an error: (400) Bad Request.
I'm kind a knewby to REST and my english is not that good... Sorry! :)
(RE)EDIT
I've tried with RestSharp and I've simplified a bit my code...
Now I'm using my access token to make the GET request.
How do I add the "authorization bearer" to my request?
Is it like this?
//Ask for the token
var client = new RestClient("https://login.windows.net/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", Request.QueryString["code"]);
request.AddParameter("redirect_uri", myRedirectUri);
request.AddParameter("client_id", myClientID);
request.AddParameter("client_secret", myClientSecret);
IRestResponse response = client.Execute(request);
string content = "[" + response.Content + "]";
DataTable dadosToken = (DataTable)JsonConvert.DeserializeObject<DataTable>(content);
//I don't need a DataTable, but it was a way to retrieve my access token... :)
//Ask for info with the access token
var client2 = new RestClient("https://outlook.office365.com/api/v1.0/me");
var request2 = new RestRequest(Method.GET);
request2.AddHeader("authorization", myToken.ToString());
//I've tried this way also:
//client2.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(dadosToken.Rows[0]["access_token"].ToString(), "Bearer");
IRestResponse response2 = client2.Execute(request2);
string content2 = "[" + response2.Content + "]";
Response.Write(content2); //this returns NOTHING!
Thanks again!
You can also use Fiddler to figure out if the Request is well formed.
Try a simpler endpoint first like: https://outlook.office365.com/api/v1.0/me
and check if the right data comes back. You can call this endpoint just from the browser and also look at the request/respond inside Fiddler.
The first thing to check: Is it a bad request. This usually means the method can't be found or the given parameters cannot be located. Check the deploy and make sure it is the most up to date version and also check that your server is actually running.
Related
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
I have a question about making an authorized call to a GET Url using RestSharp.
I have a provided basic token, which looks something like this: dGVzdG5hbWU6dGVzdHBhc3N3b3Jk.
Let's say the GET Url is: https://sometest.api.com/todos?id=1 and requires authorization.
How would I pass the above token in the above GET Url?
I tried this:
var client = new RestClient("https://sometest.api.com") // base address
var request = new RestRequest("todos?id=1"); // resource
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic dGVzdG5hbWU6dGVzdHBhc3N3b3Jk");
var response = client.Execute(request);
This does not seem to work. Do I need to add the basic token as a parameter instead, or both in the header and as parameter?
Or would I need to use the client.Authenticator on the RestClient:
client.Authenticator = new HttpBasicAuthenticator("testname", "testpassword");
Any help is appreciated, thanks.
Best Regards
Could you provide more information how did you conclude that it does not work? Any exception? An error message you could provide?
How did you get that token? What the expiration time of the token?
This is how I am doing it, pretty much like you, except I am using different token type:
var request = CreateServerRequest(_configuration.SOME_URI);
request.AddHeader("Authorization", $"Bearer {Token}");
request.AddJsonBody(request);
var server = new RestClient(_configuration.SOME_ENDPOINT);
var serverResponse = server.Execute(request);
if (serverResponse.StatusCode == HttpStatusCode.OK)
{
return new ServiceResponse<bool>(true);
}
Where the method CreateServerRequest contains only:
return new RestRequest(uri)
{
RequestFormat = DataFormat.Json,
Method = Method.POST
};
Hope this helps,
Cheers and happy coding.
I want to send a request to a rest API and get response and show it on the form. the API documentation says that I should use my token in bearer to Authorization in the header.
I've used RestSharp nugget and this my written code:
var client = new RestClient("https://api.payping.ir");
var request = new RestRequest("v1/product/List");
request.AddHeader("Authorization", "Bearer <myToken>");
request.AddParameter("offset", 0);
request.AddParameter("limit", 10);
var response = client.Execute(request, Method.GET);
richTextBox2.Text = "Status:\n" + response.StatusCode + "\nContent:\n" + response.Content + "\nResponse:\n" + response.IsSuccessful;
but I receive an incorrect response. my final string that returns on my form by this code is:
Status:
0
Content:
Response:
False
what is my mistake? and how can I get a correct response from a rest API?
thank you for your attention
Try :
request.AddParameter("Authorization", $"Bearer {myToken}", ParameterType.HttpHeader);
Then inspect your sent packet using Fiddler to verify header is sent.
Next step is server-side then ;)
I'm trying to write a C# application that will call an api for Pacer.gov. First thing I need to do it get a cookie to pass with my request. I'm using Chrome's Postman app to try to generate a POST request. Can someone explain what I'm doing wrong?
The instructions I got from Pacer.gov to get the authentication token are
For credentials, you can POST username(loginid) and password(passwd) to the authentication service here https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl
This will issue you a PacerSession cookie.
Here are some ways I tried:
(I’m just showing ##### as the login and ***** as the password, but I used the actual login and password when I tried it)
Including username and password in the URL
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-in/check-pacer-passwd.pl?loginid=#####&passwd=*****");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "a5bd0d9c-85f5-4ed6-6ad8-ac06e553f5db");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);
o Received HTML page saying “Access to PACER requires a valid account id and password. “
Including username and password in the header
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "add9dedf-10bf-eab4-428a-134c0e8a1783");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("passwd", "*****");
request.AddHeader("loginid", "#####");
IRestResponse response = client.Execute(request);
o Received HTML page saying “Access to PACER requires a valid account id and password. “
Including username and password in the body as form data
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "454a8ebd-b2b4-3db2-0c5c-c48e2964c671");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001");
request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"loginid\"\r\n\r\n#####\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"passwd\"\r\n\r\n*****\r\n-----011000010111000001101001--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
o Received message “Could not get any response”
Typing URL into Chrome with the username and password
https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl?loginid=#####&passwd=*****
o Received error “This site can’t be reached”
UPDATE - 5-31-16
I've made several more attempts, but am still not getting the cookie back. I tried this code:
var client = new RestClient("https://pacer.login.uscourts.gov");
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "#####");
request.AddParameter("passwd", "*****");
IRestResponse response = client.Execute(request);
When I look at the response, there is one cookie called JESSIONID which appears just to be a generic browser session ID, not the authentication code I'm expecting:
I'm not exactly sure what to expect from the response, but I know that a "NextGenCSO cookie" was mentioned in one of the e-mails from Pacer. If I login through the web browser and look at the cookies, I see a NextGenCSO cookie; I'm guessing I should be seeing something similar in the response from the API call:
UPDATE - 6-3-16
Thanks to help from #jonathon-reinhart, I was able to get the authentication cookie working with this code:
// Authentication
var client = new RestClient("https://pacer.login.uscourts.gov");
client.CookieContainer = new System.Net.CookieContainer();
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "#####");
request.AddParameter("passwd", "*****");
IRestResponse response = client.Execute(request);
var PacerSession = "";
foreach (RestResponseCookie cookie in response.Cookies)
{
if (cookie.Name == "PacerSession")
{
PacerSession = cookie.Value;
}
}
You are not correctly POSTing as the directions indicate.
Putting this:
https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl?loginid=#####&passwd=*****
into the address bar is not a POST. That's a GET with query string parameters.
See the RestSharp homepage for an example on how to POST:
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
You want to include loginid and passwd as data ("parameters" as RestSharp calls them), not has headers.
So you should be instead doing something like this:
var client = new RestClient("https://pacer.login.uscourts.gov");
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "####");
request.AddParameter("passwd", "****");
IRestResponse response = client.Execute(request);
I have searched high and low for an answer to this problem. Basically, I am creating a C# application which (In it's first incarnation) will authenticate with the Projectplace API which uses OAuth 1.0a. It currently returns the oauth_verifier to the address bar, but when I use the var response = request.GetResponse(); method, it returns the oauth_token and oauth token_secret which I sent as part of the authorization in the first place.
Perhaps I am misunderstanding the way this process is supposed to work, but I've read every single answer out there and none seem to address this question. Do you have to, or is it possible, to pull the verifier code from the address bar (or wherever else it can be obtained), after I have entered my username and password on the authentication page after callback URL is loaded?
I believe OAuth1.0a requires the verification code to retrieve an access token, and I cannot find a simple way to pull the verification code.
I would really appreciate any help, it's driving me nuts!!
UPDATED 03.12.12
Thanks for your response!
Essentially, I am the client attempting to retrieve the oauth_verifier from the oauth provider after sending this initial request below, my next step is to authorize then retrieve verifier. I tried the following, hopefully as you suggested, like swimming in the deep end here :)
//Generate string for initiation request.
requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
requestUri.AppendFormat("oauth_nonce={0}&", nonce);
requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp);
requestUri.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
requestUri.AppendFormat("oauth_version={0}&", "1.0");
requestUri.AppendFormat("oauth_signature={0}", signature);
var request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri.ToString()));
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var parts = queryString.Split('&');
var token = parts[1].Substring(parts[1].IndexOf('=') + 1);
var tokenSecret = parts[0].Substring(parts[0].IndexOf('=') + 1);
var queryString2 = String.Format("oauth_token={0}", token);
//AUTHORIZE WITH CREDENTIALS FROM USER.
var authorizeUrl = "https://api.projectplace.com/authorize?" + queryString;
Process.Start(authorizeUrl);`
//TRY AND READ VERIFICATION STRING AFTER AUTHORIZATION REDIRECT`
String oauthVerifier = HttpContext.Current.Request.QueryString["oauth_verifier"];
Unfortunately, once i've done this, I can't seem to get a querystring returned showing the oauth_verifier that I am clearly seeing in the string showing in the address bar. (Yes it's a very newbish way of describing it, i'm learning the code as well as OAuth :P).
Thanks for your help so far. I tried to run the above, but it just said that says "Object reference not set to an instance of an object.".
Also, if I attempt to use the previous code I used to obtain the querystring / response? from the initiation request using the following lines, the querystring3 just comes back as blank... really frustrating! :)
var queryString3 = new StreamReader(response.GetResponseStream()).ReadToEnd();
var parts3 = queryString3.Split('&');
I'm going to assume that by "in the address bar" you mean that the oauth_verifier is passed to your site from the ProjectPlace server via a query string parameter in the redirect URL. In order to read this in your C# server side code, you would use something like the following (I modified your sample code for this solution):
requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
requestUri.AppendFormat("oauth_nonce={0}&", nonce);
requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp);
requestUri.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
requestUri.AppendFormat("oauth_version={0}&", "1.0");
requestUri.AppendFormat("oauth_signature={0}", signature);
var request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri.ToString()));
//Note: this is unnecessary - GET is the default
request.Method = WebRequestMethods.Http.Get;
//By casting to HttpWebResponse you get access to the QueryString property
var response = request.GetResponse() as HttpWebResponse;
var oauthVerifier = response.QueryString["oauth_verifier"];
//The response stream contains the HTTP response body,
//which will not contain the URL to which the redirect is sent
//I'm not sure if there is anything there that you will need
var responseBody = new StreamReader(response.GetResponseStream()).ReadToEnd();
//AUTHORIZE WITH CREDENTIALS FROM USER. -- Not sure what this section is doing
var queryString = string.Format("oauth_token={0}", oauthVerifier);
var authorizeUrl = "https://api.projectplace.com/authorize?" + queryString;
Process.Start(authorizeUrl);