I have an API for getting data that is created in Swagger. I Only have an base URL and an username, password and a token for that. When I go to the URL it will go to a login page and after login, We can access a list of APIs and get data from that.
Now I need that to be done in C# using restsharp. So that I can get the result in JSON and can update the values to DB.
This is my code which I used in C#
var restClient = new RestClient("https://v3.fusesport.com/api/events/")
{
Authenticator = new HttpBasicAuthenticator("xxxxx", "xxxxx")
};
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("content-type", "application/json");
IRestResponse response = client.Execute(request);
This is getting an connection closed error.
I tried the API in postman app in chrome, it is getting the below error.
{
"detail": "Authentication credentials were not provided."
}
This is the screenshot of postman call with token
Postman with token
This is the screenshot of postman call with basic authentication
enter image description here
Can you help me what I am doing wrong. I think the API is using session based authentication.
Thanks in Advance.
I think your headers are incorrect. Instead of
request.AddHeader("Token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
try adding
request.AddHeader("Authorization", "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b");
Related
good day. I’m new to C# and OAuth. I'm trying to implement OAuth2 in Blazor using RestSharp. I have the following code:
#page "/infusionsoft"
#using System.Globalization
Infusionsoft
Request authentication
#code {
#using RestSharp;
#using RestSharp.Authenticators;
#using Newtonsoft.Json;
public void Foo1()
{
string url = "https://signin.infusionsoft.com/app/oauth/authorize";
string client_id = "myid";
string client_secret = "mysecret";
//request token
var restclient = new RestClient(url);
RestRequest request = new RestRequest("request/oauth") { Method = Method.POST };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("client_id", client_id);
request.AddParameter("client_secret", client_secret);
request.AddParameter("grant_type", "authorization_code");//+
IRestResponse tResponse = restclient.Execute(request);
Console.WriteLine(tResponse.Content);
}
}
It’s supposed to redirect my app to a sign in page but right now it doesn’t do anything. I have tried google but I still don’t get it :(. Also, how do I start calling the apis once I get the authorization. Any sample code is greatly appreciated. Thanks.
You should redirect the user to authentication server by sending
HTTP status code 302 and then specifying the auth server URL and query parameters in Redirect URL.
I'm not overly familiar with the things you're using, but from what I can tell, you aren't actually redirecting at all.
You're sending the POST request to the OAuth URL using RestSharp which doesn't redirect the user and instead just sends the request from your application and saves the response in tResponse.
It seems like you'll need to use IUriHelper#NavigateTo(url) to redirect to the OAuth page. You can inject it using #inject IUriHelper uriHelper, then build the URL with its parameters, and then pass it uriHelper.NavigateTo(url).
Hope this helps.
Links:
Redirecting in blazor with parameter
https://medium.com/cloudnimble/redirects-in-blazor-apps-75b3f4709d57
I am following the Yahoo official documentation (https://developer.yahoo.com/oauth2/guide/openid_connect/getting_started.html). I can successfully get an authorization code after user logins with Yahoo. I am now at step 3, trying to exchange the authorization code for a token, but Yahoo keeps returning an http error 500.
To exchange the authorization code for the access token from Yahoo, I am using the following RestSharp syntax:
var client = new RestClient(provider.TokenUrl);
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddParameter("client_id", codeModel.clientId, ParameterType.GetOrPost);
request.AddParameter("client_secret", provider.Secret, ParameterType.GetOrPost);
request.AddParameter("code", codeModel.code, ParameterType.GetOrPost);
request.AddParameter("grant_type", "authorization_code", ParameterType.GetOrPost);
request.AddParameter("redirect_uri", codeModel.redirectUri, ParameterType.GetOrPost);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
var response = client.Execute<TokenResponseModel>(request);
responde.data returns the following:
content: {"error":"ACCESS_TOKEN_GENERATION_FAILED","error_description":"Access token generation failed"}
StatusCode: InternalServerError
The official documentations states: "The request parameters below are transmitted using HTTP POST in the request body. You can, however, also send the parameters client_id and client_secret in the HTTP Headers instead".
I have tried both methods (clientid and secret as part of the body and as an Basic Authorization Header) and both return the same result.
When sending the clientid and secret as part of the Basic Authorization header, both parameters above are replaced by the following:
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(codeModel.clientId, provider.Secret);
As stated before, the only message returned by Yahoo is "internal server error".
Is there something wrong with the RestSharp syntax that could be causing this? Any other ideas will be greatly appreciated.
Needless to say, all parameters of the request contain the data they need.
Thanks
When you create your application profile at YDN you must make sure to select at least one API permission. For example try "Profiles (Social Directory) Read Public".
If your application has no API permissions then token generation will fail just the way you described.
If you already created an application with no permissions then you will have to delete it and create it again.
I'm trying to access a website that requires login via a form.
I used the Postman HTTP client.
I tried to do the normally http post request but didn't seem to work, I get a successful status code (200 OK) but it doesn't log in, eventually did work with a GET request with BODY parameters (I hadn't seen GET request with body parameters).
Well, I tried to simulate this request in C# code with no luck, I even tried the generated code that Postman offers with no luck again.
Down below is the Postman request and the C# code snippet based on auto-generated Postman code. Does anyone know if is there to make this request with any library or if there is something that I miss?
Thank you in advance.
var client = new RestClient("https://thessalia-3.teilar.gr/login.asp");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Referer", "https://thessalia-3.teilar.gr/login.asp");
var parameters = new Dictionary<string, string>();
parameters["userName"] = JsonConvert.SerializeObject("myusername");
parameters["pwd"] = JsonConvert.SerializeObject("mypass");
parameters["loginTrue"] = JsonConvert.SerializeObject("extravalue");
var content = new FormUrlEncodedContent(parameters);
request.AddParameter("application/x-www-form-urlencoded", content);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.WriteLine(response.StatusCode);
Postman Request Photo
Edit:
Postman Request Body Parameters
I've also tried to run this but also not logged in.
Auto-generated code form Postman
If the request was successful (200) and you got the HTML page for "Invalid Credentials", then your code that's making the request should be fine and the issue is with the credentials. Like I said in my first comment, don't serialize the parameters to JSON, URL-encode them instead:
parameters["userName"] = HttpUtility.UrlEncode("myusername");
parameters["pwd"] = HttpUtility.UrlEncode("mypass");
parameters["loginTrue"] = HttpUtility.UrlEncode("extravalue");
This is the standard way and it works with writing the parameters directly to the request stream, or with a utility class like StringContent. However, since you're using the utility class FormUrlEncodedContent, it URL-encode them for you, so you don't have to. In that case, simply assign them directly as string:
parameters["userName"] = "myusername";
parameters["pwd"] = "mypass";
parameters["loginTrue"] = "extravalue";
I need to retrieve token from link.
But when I enter valid username and password I do not see any token. Also I tried to retrieve it in my C# Android program.
`var client = new RestClient("https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData");
request.AddParameter("username", login);
request.AddParameter("password", password);
IRestResponse response = client.Execute(request);
var content = response.Content;`
There are a lot of data in output but there is no token. How can I get deal with it?
The request URL is wrong.
https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData
is just a documentation page (aka Swagger UI), not the actual request URL.
To find out the actual URL, use Swagger UI's "Try it out" feature: fill out the operation parameters and click "Try it out". It looks like the correct URL is
https://networkrail-uk-qa.traffilog.com/UK/api/User/Login?username={login}&password={password}
where the login and password need to be URL-encoded.
Also note the request HTTP method (POST), and that the parameters need to be passed in the query string. With all that in mind, your code should be:
var client = new RestClient("https://networkrail-uk-qa.traffilog.com");
var request = new RestRequest("UK/api/User/Login", Method.POST);
request.AddQueryParameter("username", login);
request.AddQueryParameter("password", password);
IRestResponse response = client.Execute(request);
I'm using Trello's Developer API's implementation of OAuth to post stuff to a list.
I've successfully made a request and got my oauth_token and oauth_token_secret back from https://trello.com/1/OAuthGetRequestToken
But when I call https://trello.com/1/OAuthAuthorizeToken, passing the oauth_token that I've just received, I get a response of 'App not found'.
Can anyone help?
EDIT: Here's what I'm getting back from https://trello.com/1/OAuthGetRequestToken
oauth_token=8d0e43fd0cc67726567d49ae5e818852&oauth_token_secret=[secret]
And here's the Authorization header I'm sending (escaped in C#)
"OAuth oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\", oauth_nonce=\"8335006\", oauth_timestamp=\"1414663625\", oauth_consumer_key=\"9612eaca23c7bdd3eca60dc8c2a8159c\", oauth_signature=\"M6sLyyfHGYXOtQnLJexDx96kbFo=\", oauth_token=\"8d0e43fd0cc67726567d49ae5e818852\""
Am I doing something wrong or is this an error on Trello's end?
EDIT: I'm using RestSharp to call the Trello API, as below:
var client = new RestSharp.RestClient("https://trello.com/");
var request = new RestSharp.RestRequest("1/OAuthAuthorizeToken", Method.GET);
EDIT: Here's the complete RestSharp code:
var client = new RestSharp.RestClient("https://trello.com/");
var request = new RestSharp.RestRequest("1/OAuthAuthorizeToken", Method.GET);
Uri uri = new Uri(string.Format("{0}/{1}", client.BaseUrl, request.Resource));
string authHeader = GenerateAuthorizationHeader(uri);
//This is the output of GenerateAuthorizationHeader()
//string authHeader = "OAuth oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\", oauth_nonce=\"8335006\", oauth_timestamp=\"1414663625\", oauth_consumer_key=\"9612eaca23c7bdd3eca60dc8c2a8159c\", oauth_signature=\"M6sLyyfHGYXOtQnLJexDx96kbFo=\", oauth_token=\"8d0e43fd0cc67726567d49ae5e818852\"";
request.AddHeader("Authorization", authHeader);
The GenerateAuthorizationHeader method uses OAuth.OAuthBase to generate the TimeStamp and Signature for the OAuth request.
Looks like it might be a trello problem...
this user, had the wrong key by the sounds of things.
are you 100% sure that the key is correct.
Getting "App not found" from Trello Authentication
I had the same problem, the thing here is that OAuth is version 1.0
When you get the token and token secret from the first call you have to make your user to visit https://trello.com/1/OAuthAuthorizeToken not you.
In your case you have to redirect your user to https://trello.com/1/OAuthAuthorizeToken?oauth_token=8d0e43fd0cc67726567d49ae5e818852&scope=read,write,account
He will get a page where he can Allow the access. Then you will get a verification code in the page after the authorization to continue with your process (GetAccessToken).
You can try this as a test, in a real application you have to specify a callback url and an application name in the OAuthAuthorizeToken call.