I try to connect my home automation in c# with Withings but I don't achieve to do this.
I try this library but it doesn't work, the URL doesn't contain key or secret.
I try to use RestSharp :
RestClient client = new RestClient(baseUrl)
{
Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
};
RestRequest request = new RestRequest("account/request_token", Method.POST);
IRestResponse response = client.Execute(request);
NameValueCollection qs = HttpUtility.ParseQueryString(response.Content);
string oauthToken = qs["oauth_token"];
string oauthTokenSecret = qs["oauth_token_secret"];
PackageHost.WriteInfo("{0}", response.Content);
const string verifier = "5179055";
request = new RestRequest("account/access_token");
client.Authenticator = OAuth1Authenticator.ForAccessToken(
consumerKey, consumerSecret, oauthToken,
oauthTokenSecret, verifier);
response = client.Execute(request);
Assert.NotNull(response);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
qs = HttpUtility.ParseQueryString(response.Content);
oauthToken = qs["oauth_token"];
oauthTokenSecret = qs["oauth_token_secret"];
I succeed to authorize my application but I don't get the access token or secret. It says "Invalid verifier" but I get this verifier from authorization page, in url.
Anyone succeed to connect Withings with .net ?
Thank for your help.
I've been having the same issue. I decided on using Quantfabric. You can see my post on Medium, for instructions on how to use.
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
Basically, I've been trying to authenticate through oauth2 on c# using restsharp, but I am receiving a bad request response, I'm not sure if it's something related to the API configuration or if it's something I'm missing In my code.
public string getToken(string email, string password)
{
var restclient = new RestClient(loginUrl);
RestRequest request = new RestRequest("request/oauth") { Method = Method.GET };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("email", HttpUtility.UrlPathEncode(email));
request.AddParameter("password", HttpUtility.UrlPathEncode(password));
request.AddParameter("grant_type", HttpUtility.UrlPathEncode("password"));
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
string token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
this is the response when I execute that code
An this is the postman execution
Thanks!
I think there problem with adding parameters the way you are adding.
latest restsharp support this,
Also,avoid encoding of params by setting to false
var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test#test.com",false);
var restclient = new RestClient(loginUrl); I think you need to check your url.
Try this.. you OAuth is password grantype are your sure your not missing any credentials like client_id, scope and client_secret.
public static string getAccessToken(string usern, string pswd)
{
RestClient client = new RestClient(ConfigurationManager.AppSettings["TokenUrl"]);
RestRequest request = new RestRequest() { Method = Method.GET};
request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
request.AddParameter("username", usern, ParameterType.GetOrPost);
request.AddParameter("password", pswd, ParameterType.GetOrPost);
IRestResponse response = client.Execute(request);
var responseJson = response.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
I want to skip AWS Cognito's Hosted UI for login/authorization. However, when I try to consume the login end point to fetch authorization-code, I'm slapped with MethodNotAllowed response. As per AWS documentation, the login end-point accepts "Get" requests only. Based on my research on this topic, I figured it was possible to use "Post" method with login credentials for the login end point (Thanks to AWS documentation).
Can someone help please me figure out the issue?
AWS Pool Settings:
AWS Pool Settings
C# Code:
I'm using RestSharp as the HTTP client.
private static void CognitoOAuthSignIn(string username, string password)
{
var CLIENT_ID = "<client_id>";
var RESPONSE_TYPE = "code";
var REDIRECT_URI = "https://www.google.com";
var SCOPE = "openid";
var AUTH_DOMAIN = "https://<domain_name>.auth.us-east-1.amazoncognito.com";
var USERNAME = username;
var PASSWORD = password;
RestClient client = null;
// 1. Get XSRF Code
var csrfRequestUrl = $"{AUTH_DOMAIN}/oauth2/authorize?response_type={RESPONSE_TYPE}&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}";
var csrfRequest = new RestRequest(Method.GET);
client = new RestClient(csrfRequestUrl);
client.CookieContainer = new CookieContainer();
IRestResponse csrfResp = client.Execute(csrfRequest);
var cookie = client.CookieContainer.GetCookieHeader(new Uri(AUTH_DOMAIN));
var code = cookie.Split(';')[0].Substring(11);
// 2. Make login request
var loginRequestUrl = $"{AUTH_DOMAIN}/login?client_id={CLIENT_ID}&response_type={RESPONSE_TYPE}&scope={SCOPE}&redirect_uri={REDIRECT_URI}";
client = new RestClient(loginRequestUrl);
client.DefaultParameters[0].Value = "*/*"; // Setting "Accept" header
client.AddDefaultHeader("Content-Type", "application/x-www-form-urlencoded");
client.AddDefaultHeader("Accept-Encoding", "gzip,deflate");
client.AddDefaultHeader("Accept-Language", "en-US");
client.AddDefaultHeader("Cache-Control", "no-cache");
client.AddDefaultHeader("Cookie", $"csrf-state=; csrf-state-legacy=; XSRF-TOKEN={code}");
var authCodeRequest = new RestRequest(Method.POST);
authCodeRequest.AddParameter("_csrf", code, ParameterType.GetOrPost);
authCodeRequest.AddParameter("username", USERNAME, ParameterType.GetOrPost);
authCodeRequest.AddParameter("password", PASSWORD, ParameterType.GetOrPost);
authCodeRequest.RequestFormat = DataFormat.None;
IRestResponse authCodeResp = client.Execute(authCodeRequest);
Console.WriteLine(authCodeResp.StatusCode); //returns MethodNotAllowed
}
So here's my code that I'm trying.
Uri uri = new Uri(_environmentConfiguration.AuthorityLoginRequestUrl);
string content = $#"Username={ userID }&Password={ userPassword }";
var request = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
_httpClient.SetBearerToken(token.AccessToken);
var response = await _httpClient.PostRequest(uri, request);
The response I get back is a status 400: Bad Request.
Obviously there is something wrong with the request. Either headers/cookies and/or query.
Any ideas?
I have to upload files to box.com for that i need authorize and get accesstoken and refresh token. I am not finding any code in c# asp.net.i want code for authentication using c# and asp.net and code for getting accesstoken and refresh token. I tried below code am getting error as page is Expired request again.
Here is the code in c# asp.net.I am trying using Restsharp
public void GetAccessToken(string code, string ClientId, string ClientSecret)
{
RestClient rs = new RestClient();
string grant_type = "authorization_code";
RestRequest request = new RestRequest(Method.POST);
IRestRequest reuest = request;
string strHeaders = null;
RestResponse response = default(RestResponse);
IRestResponse resp = response;
string strResponse = null;
try
{
rs.BaseUrl = "https://www.box.com/api/oauth2/token";
request.Resource = "oauth2/token";
strHeaders = string.Format("grant_type={0}&code={1}&client_id={2}&client_secret={3}", grant_type, code, clientId, Clientsecret);
request.AddHeader("Authorization", strHeaders);
resp = rs.Execute(reuest);
strResponse = resp.Content;
Label1.Text = strResponse;
}
catch (Exception ex)
{
throw ex;
}
}
From the documentation:
https://developers.box.com/oauth/
(See "Getting the Access Token")
When exchanging an auth code for a set of access tokens and refresh tokens, you need to make a POST request to the https://www.box.com/api/oauth2/token endpoint.
Try taking what you're adding in the "Authorization" part of your header, and putting it in a URL encoded POST body.
Or even better, try the available .NET SDK which will handle this very part of the OAuth workflow for you:
https://github.com/box/box-windows-sdk-v2
You also need to set the encoding with:
request.RequestFormat = DataFormat.Xml;