RestSharp with JWT - c#

I am trying to create JWT for authenticating REST api. Please find my code below.
private static string getJWT()
{
var client = new RestClient("https://itsmtest-app.XXXXXX.com/api/jwt/login");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("username", "testuser",ParameterType.RequestBody);
request.AddParameter("password", "Passw0rd",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content;
}
I am getting an error. please find response.Content as below. But the rest call working fine in postman even I copied the code postman.
Error 406 Not Acceptable
HTTP ERROR 406
Problem accessing /api/jwt/login.
Reason:Not Acceptable

Related

'invalid_grant' error on API call with RestSharp

I need to convert that curl request to c#. Im using RestSharp. curl request:
> curl -X POST -i https://gw.api.alphabank.eu/sandbox/auth/token \
-u "{{client_id}}:{{client_secret}}" \
-d "grant_type=client_credentials&scope=account-info-setup"
I tried the following code but I end up with 'invalid_grant' error as a response.
Any ideas what i'm doing wrong?
My code:
var client = new RestClient(url);
var request = new RestRequest();
request.Method = Method.POST;
client.Authenticator = new HttpBasicAuthenticator(ABclientID, ABclientSecret);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("scope", "account-info-setup");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/x-www-form-urlencoded"; };
IRestResponse response = client.Execute(request);
this sample code is generated by Postman and it's working for my api which accepts application/x-www-form-urlencoded, can you add your parameters like this? Or create and make your request works on Postman and generate to C#-RestSharp it's usually works for me with minor changes.
var client = new RestClient("url");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("userId", "1234");
request.AddParameter("count", "5");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Turns out "invalid_grant" meant wrong credentials. I was giving wrong client-secret.
Request was succesfull after correcting the client_secret.

How to troubleshoot 502 Bad Gateway error

I have
curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --data-binary "username=xx#xxtemple.net&password=XXXXXXXX" 'https://api.xxsuccess.com/v1/auth'
running without ANY errors and go what I want.
When I run the following C# code on the SAME machine, I got 502 Bad Gateway Error:
string requestUri = "https://api.xxsuccess.com";
var client = new RestClient(requestUri);
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("xx#xxtemple.net", "XXXXX");
var request = new RestRequest("v1/auth", Method.POST);
IRestResponse restResponse = client.Execute(request);
Any idea how troubleshoot the problem ?
Why "Curl" is working and the code is not.
--data-binary does POST the data (in this case your username and password) in the request body. HttpBasic Authentication puts your authentication info into the Authorization header. So these are different requests.
If the first request is working, you need to put the data in the body also for the RestSharp request
var client = new RestClient(requestUri);
var request = new RestRequest("v1/auth", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("username","yourusername", ParameterType.GetOrPost);
request.AddParameter("password","yourpassword", ParameterType.GetOrPost);

Retaining authorization header in RestSharp during redirects

I am using RestSharp to make a GET api call. The api call is authenticated through HTTP Basic authentication by passing the authorization header.
The server redirects the api call with a status code 307. My client code does handle the redirects but the authorization header is not passed to this redirected api call. This is done for valid reasons as mentioned here. Hence I do get an unauthorized error.
How can I configure the RestClient to restore the authorization header?
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I added a check that resends the api request of receiving a 401 with the below code.
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
//Resend the request if we get 401
int numericStatusCode = (int)response.StatusCode;
if(numericStatusCode == 401) {
var redirectedClient = new RestClient(response.ResponseUri.ToString());
IRestResponse newResponse = redirectedClient.Execute(request);
Console.WriteLine(newResponse.ResponseStatus);
}

Convert Postman code to regular C# code

var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "0e4d8dba-29da-0b26-1b43-1bf974e9b5de");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
I can send request successfully and login to site in postman, but I can't do it in VS. This is my code in VS:
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddParameter("IsPersistent", true, ParameterType.GetOrPost);
request.AddParameter("Password", "myPass", ParameterType.GetOrPost);
request.AddParameter("UserName", "myUsername", ParameterType.GetOrPost);
request.AddParameter("returnUrl", "/Account/Login", ParameterType.GetOrPost);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
but I get "unauthorized" message (401) in VS
you can use PostMan Auto C# Code generator
I believe your issue is that you're adding things that should be part of the body as parameters (based on the screenshot from PostMan showing these items as part of the body). This is untested but may work for you.
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddBody(new
{
IsPersistant = true,
Password = "myPass",
UserName = "myUsername",
returnUrl = "/Account/Login"
});
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
You probably need to do a GET of the page first, then when making then POST reflect back all cookies received during the GET (if that RestClient of yours doesn't do that automatically).
Login pages typically add a cookie during GET and expect that cookie during POST to prevent XSRF (this involves including that same token as a form's hidden field, although the XSRF token is apparently not present in your Postman payload). It also wouldn't surprise me that some cookie-based sessionID filter is blocking you even before your request hits the login controller/middleware. In any case, doing the GET first and then reflecting the cookies in POST should work.

oAuth uStream API

I'm trying to get data from uStream using their API and oAuth. I can get the auth token and that token does work in Rest API Client and I can get data. I however cannot get data in my project... I keep getting 401 unauth..
Code:
protected void Page_Load(object sender, EventArgs e)
{
var client = new RestClient("https://www.ustream.tv/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic xxxxxxxxxxxxxxxxxx");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "client_secret=xxxxxxxxxxxxx&client_id=xxxxxxxxxxxx&grant_type=client_credentials&=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
IRestResponse<TokenObject> response2 = (IRestResponse<TokenObject>)client.Execute<TokenObject>(request);
var tknName = response2.Data.access_token;
GetData(tknName);
}
public void GetData(string token)
{
var client = new RestClient("https://api.ustream.tv/channels/206844441.json");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer" + token);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse jsonResponse = client.Execute(request);
IRestResponse<Channel> json2Response2 = (IRestResponse<Channel>)client.Execute<Channel>(request);
var blah = json2Response2.Content;
}
The jsonResponse comes back 401... but I can use the token in API client like Insomnia and it will work... I can get data.
Any ideas on what I'm doing wrong?
Thanks!
Assuming token is not prefixed with a single space, then this line:
request.AddHeader("authorization", "Bearer" + token);
Should instead be (added a space after Bearer):
request.AddHeader("authorization", "Bearer " + token);
Additionally, the GET request for data does not require the Content-Type header to be added to the request; although including is unlikely to cause an error.
As João mentioned, the main problem will be the missing space character between the string "Bearer" and the token itself . After you fix this i'm pretty sure it will work.
Yes, Content-Type is superfluous for GET request, but it does not harm the success of your request.
In addition, you don't need to provide client secret twice. That's enough to provide it through the Authorization header or the client_secret property in the request body.
So, that's enough to provide the secret that way:
request.AddHeader("authorization", "Basic xxxxxxxxxxxxxxxxxx");
Ant in this case you shouldn't provide the secret again in the request body, here's the modified call, based on the original code:
request.AddParameter("application/x-www-form-urlencoded", "client_id=xxxxxxxxxxxx&grant_type=client_credentials&=", ParameterType.RequestBody);
There were actually two things I had wrong. First one pointed out by #João Angelo was the missing space between the string: Bearer & token.
Second and most frustrating was that authorization needed to be Authorization... with the capital A. Now it works... .Thanks for the help.

Categories

Resources