Get an access token from sign now REST APIs? - c#

I followed this procedure.
https://techlib.barracuda.com/CudaSign/RestEndpointsAPI
This is my C# code to get an access token.
string userData = "username=email#domain.com&password=mypassword&grant_type=password";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://signnow.mydomain.com/api/index.php/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "Basic " + userData);
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
//JSON output.
}
The following error I got:
The remote server returned an error: (400) Bad Request.
I know this is because of wrong pattern. Can you please help me in getting an access token from sign now?
Thanks in advance!!!
cURL Request:
string data = "username=email#domain.com&password=mypassword&grant_type=password";
WebRequest myReq = WebRequest.Create(myURL + "oauth2/token");
myReq.Method = "POST";
//myReq.ContentLength = data.Length;
myReq.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding enc = new UTF8Encoding();
//myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(data)));
myReq.Headers.Add("Authorization", "Basic " + data);
WebResponse wr = myReq.GetResponse();

As far as I can see, the user data should be sent within the payload and not within the header Authorization. The client credentials (ENCODED_CLIENT_CREDENTIALS) must be something associated to your global account on Barracuda.
I suggest you to test your request using curl since the documentation of the tool use it:
curl -H 'Authorization: Basic ENCODED_CLIENT_CREDENTIALS'
--data 'username=user#test.com&password=test&grant_type=password&scope=user%20documents%20user%2Fdocumentsv2' https://capi-eval.signnow.com/api/oauth2/token
The command parameter --data corresponds to the payload of the request POST.
To fix your problem, you shoud update your code as described below:
string encodedUserCredentials =
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
string userData = "username=email#domain.com&password=mypassword&grant_type=password";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://signnow.mydomain.com/api/index.php/oauth2/token");
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "Basic " + encodedUserCredentials);
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(userData);
requestWriter.Close();
var response = request.GetResponse() as HttpWebResponse;
To know what to put within the variable encodedUserCredentials (i.e. values of user and password), see this doc https://techlib.barracuda.com/CudaSign/RestEndpointsAPI#, section "Security and Access Control".
See these two links for more details:
How to pass POST parameters to ASP.Net web request?
How to send authentication header in ASP.Net for set of web request
Hope it helps you,
Thierry

Ok, this may not be the most elegant solution, but I am new to all this. Also I apologize about it being in vb instead of C#
Public Class iqAPI
Public Shared Function postRequest(ByVal url As String, ByVal toSerialize As String, strHeader As String) As DataTable
Dim wHeader As WebHeaderCollection = New WebHeaderCollection
wHeader.Clear()
wHeader.Add(strHeader)
Dim wReq As WebRequest = WebRequest.Create(url)
Dim postData As String = JsonConvert.SerializeObject(toSerialize)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
wReq.Headers = wHeader
wReq.Method = "POST"
wReq.ContentType = "application/x-www-form-urlencoded"
wReq.ContentLength = byteArray.Length
Dim dataStream As Stream = wReq.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim wResp As WebResponse = wReq.GetResponse()
MsgBox(CType(wResp, HttpWebResponse).StatusDescription)
dataStream = wResp.GetResponseStream()
Using reader As New StreamReader(dataStream)
Dim respFromServer As String = reader.ReadToEnd()
Dim dtCudaClient As DataTable = JsonConvert.DeserializeObject(Of DataTable)("[" & respFromServer & "]")
MsgBox(dtCudaClient.Rows(0).ToString)
iqSTAMP.gvCudaClients.DataSource = dtCudaClient
reader.Close()
dataStream.Close()
wResp.Close()
Return dtCudaClient
End Using
Return Nothing
End Function
A couple things to note, I overloaded this to use an object instead of the string for the toSerialize. It seems when you create a user, you have to have it in a json format and when you are getting a Token you use the above method passing a string the way you have it. I couldn't figure out the create user without having an object that got Serialized into json.
As far as the Encoded_Client_Credentials, that is supplied by CudSign. I am currently trying to figure out how to POST a file to them without much luck. Hope you have an easier time than me.

var client = new RestClient("https://api-eval.signnow.com/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("authorization", "Basic BASE64_ENCODED_CLIENT_ID:CLIENT_SECRET");
request.AddParameter("application/x-www-form-urlencoded", "username=EMAIL&password=PASSWORD&grant_type=password", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
It looks like you are hitting the wrong endpoint to me but not 100% sure. I added the code that works for me in getting the correct response, minus some minor info. Let me know if this helps if not I am happy to help get the correct response.
Side note: might need to clear cache if anything could be saved from previous attempts.
Side note: you do not need to specify the scope if you are getting an unrestricted access token.

Related

OneLogin Create Session Login Token API returns status 400 with message: Bad Request

I am developing a C# application which needs to use the onelogin API to retrieve a session token. I am able to authenticate and and create a token with the following code:
WebRequest Authrequest = WebRequest.Create("https://api.us.onelogin.com/auth/oauth2/token");
Authrequest.Method = "POST";
Authrequest.ContentType = "application/json";
Authrequest.Headers.Add("cache-control", "no-cache");
Authrequest.Headers.Add("Authorization: client_id:XXXXXXX7bbf2c50200d8175206f664dc28ffd3ec66eef0bfedb68c3366420dc, client_secret:XXXXXXXXXX6ba2802187feb23f6450c6812b8e6639361d24aa83f12010f ");
using (var streamWriter = new StreamWriter(Authrequest.GetRequestStream()))
{
string Authjson = new JavaScriptSerializer().Serialize(new
{
grant_type = "client_credentials"
});
streamWriter.Write(Authjson);
}
WebResponse AuthReponse;
AuthReponse = Authrequest.GetResponse();
Stream receiveStream = AuthReponse.GetResponseStream ();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream);
JObject incdata = JObject.Parse(readStream.ReadToEnd());
string sToken = incdata["data"][0]["access_token"].Value<string>();
AuthReponse.Close();
However, when running the Create Session Login Token with the following code, it only returns a 400 error, and the message has no detail. Just Bad Request:
//Get the session token for the specified user, using the token recieved from previous web request
WebRequest request = WebRequest.Create("https://api.us.onelogin.com/api/1/login/auth");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("authorization", "bearer:" + sToken);
using (var streamWriter2 = new StreamWriter(request.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(new
{
username_or_email = sUsername,
password = sPassword,
subdomain = "comp-alt-dev"
});
streamWriter2.Write(json);
}
WebResponse response;
response = request.GetResponse();
string streamText = "";
var responseStream = response.GetResponseStream();
using (responseStream)
{
var streamReader = new StreamReader(responseStream);
using (streamReader)
{
streamText = streamReader.ReadToEnd();
streamReader.Close();
//
}
responseStream.Close();
}
Any ideas?
-Thank you
Also for anyone who may be getting this error. in C# the email is case sensitive. I tried User.email.com. In onelogin it was saved as user#email.com. changing the c# to lower case fixed it.
Can you let us know what payload you're sending across the wire to the .../1/login/auth endpoint as well as the response (either as others have suggested as packet snoop, or just as a debug output from the code)
400 means either bad json or the endpoint requires MFA, so this will narrow it down.
~thanks!
Just joining the troubleshooting effort =) -- I can replicate a 400 Bad Request status code with a "bad request" message when the request body contains a username_or_email and/or subdomain value that does not exist, or if the request body is empty.
Can you post what goes over the wire to the OneLogin endpoint...
OK Thanks. So it appears your subdomain does not exist. If you give me an email in the account I can find the correct subdomain value for you.

Send Message using a WebRequest and Twilio

I'm need to send a message using Twilio services and the NetDuino.
I know there is an API that allows to send messages but it uses Rest-Sharp behind the scene which is not compatible with the micro-framework. I have try to do something like the below but I got a 401 error (not authorized). I got this code form here (which is exactly what I need to do)
var MessageApiString = "https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/SMS/Messages.json";
var request = WebRequest.Create(MessageApiString + "?From=+442033*****3&To=+447*****732&Body=test");
var user = "AC4*************0ab05bf";
var pass = "0*************b";
request.Method = "POST";
request.Credentials = new NetworkCredential(user, pass);
var result = request.GetResponse();
Twilio evangelist here.
From the code above it does not look like you are replacing the {AccountSid} token in the MessageApiString variable with your actual Account Sid.
Also, it looks like you are appending the phone number parameters to the URL as querystring values. Because this is a POST request I believe you need to include these as the request body, not in the querystring, which means you also need to set the ContentType property.
Here is an example:
var accountSid = "AC4*************0ab05bf";
var authToken = "0*************b";
var MessageApiString = string.Format("https://api.twilio.com/2010-04-01/Accounts/{0}/SMS/Messages.json", accountSid);
var request = WebRequest.Create(MessageApiString);
request.Method = "POST";
request.Credentials = new NetworkCredential(accountSid, authToken);
request.ContentType = "application/x-www-form-urlencoded";
var body = "From=+442033*****3&To=+447*****732&Body=test";
var data = System.Text.ASCIIEncoding.Default.GetBytes(body);
using (Stream s = request.GetRequestStream())
{
s.Write(data, 0, data.Length);
}
var result = request.GetResponse();
Hope that helps.

save picture in cloud

I am saving data on Buddy cloud. Earlier I was saving string data and it was fine. Now I have to save picture but I am getting exception "Bad Request". Actually, they specify that its type should be "file". I don't know how to specify that. Below is the code and I have to do this using API.
documentation: http://dev.buddyplatform.com/Home/Docs/Create%20Picture/HTTP?
byte[] image = File.ReadAllBytes(imagePath);
string url = "https://api.buddyplatform.com/pictures";
// how to specify type below line ? how to correct ?
string parameters = "{data:'" + image + "'}";
HttpWebRequest request = null;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
request.Headers.Add("Authorization", "Buddy " + SharedData.buddyTOKEN);
// send request
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
// get response
response = (HttpWebResponse)await request.GetResponseAsync();
You won't be able to create the request body (your parameters string) by concatenating a string with a byte[]. This will end up calling ToString() on a byte[], leaving you with a request that looks like:
{ data:'System.Byte[]' }
Since this is being sent as a JSON request, it's likely that Buddy is expecting a base64 encoded file. This is how you would encode your file in base64 and insert it into the request:
string parameters = "{data:'" + Convert.ToBase64String(bytes) + "'}";
Result:
{data:'FxgZGurnIBlBCtIAIQ[...rest of your file...]'}

rest api is not giving desired results

I am not getting the results that documentation says. I login the Buddy; created application; copy this URL and assign to url string; when I execute the program I am not getting results that are expected (status + Accesstoken) as documentation says. Can anyone please tell me if I am missing something as newbie to http calls. Its running on http requester but not on Poster firefox add-on!
Documentation
http://dev.buddyplatform.com/Home/Docs/Getting%20Started%20-%20REST/HTTP?
Code
string parameters = "{appid:'xxxxxx', appkey: 'xxxxxxx', platform: 'REST Client'}";
private async void SimpleRequest()
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse) await request.GetResponseAsync();
}
catch (Exception)
{ }
}
Using the HTTP requester add-on on Firefox, I successfully retrieved an access token so their API work.
In C# they provide a line of code to submit your appid and appkey, that might be the problem :
Buddy.Init("yourAppId", "yourAppKey");
My guess is you have to use their .NET SDK!
You can certainly use the REST API from raw REST the way you're doing, though the .NET SDK will handle some of the more complex details of changing service root. I ran your code using my own Buddy credentials and I was able to get JSON containing an Access Token back. You may need to read the response stream back as JSON to retrieve the access token. I used the following code to dump the JSON to the console:
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
Console.WriteLine(await new StreamReader(response.GetResponseStream()).ReadToEndAsync());
Using Newtonsoft.Json I can parse out my accessToken like this:
Uri url = new Uri("https://api.buddyplatform.com/devices");
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
var parsed = JsonConvert.DeserializeObject<IDictionary<string,object>>( (await new StreamReader(response.GetResponseStream()).ReadToEndAsync()));
var accessToken = (parsed["result"] as JObject).GetValue("accessToken").ToString();
Console.WriteLine(accessToken);
The 3.0 SDK does all of this for you while exposing the rest of the service through a thin REST wrapper, the migration guide for the 3.0 SDK should help with this.

Foursquare checking using API

I am trying to checkin to Foursquare using the API, I have obtained the oauth_token and am doing a POST request with the oauth_token. According to the documentation the endpoint I'm hitting is https://api.foursquare.com/v2/checkins/add. This however returns a 400 Bad Request message. This is my code in C#
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.foursquare.com/v2/checkins/add?oauth_token"+ oauth_token + "&venueId=" + venueId);
request.Method = "POST";
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
When I do the same in curl however, it posts a checkin and I get a json response back
curl --data "oauth_token=[oaut_token]&venueId=[venueId]" https://api.foursquare.com/v2/checkins/add
Ultimately what worked is the following:
using (WebClient wc = new WebClient())
{
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("oauth_token", oauth_token);
reqparm.Add("venueId", venueId);
byte[] responsebytes = wc.UploadValues(URI, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
Thanks everyone for your help!
You should write your data to request input stream: HttpWebRequest.GetRequestStream()

Categories

Resources