How to set security/Authorisation Token in Post request of Rest Assured using selenium - rest-assured

Please suggest how i can set Security token for below code
RestAssured.baseURI ="http://qa.bridge2capital.com";
RestAssured.port = 9099;
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("UserName", "10111");
requestParams.put("Password", "123568");
request.header("Content-Type", "application/json");
request.body(requestParams.toString());
Response response = request.post("/entrepreneur/consolidatedEodTrigger");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "200");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");

You can use below code to set basic token:
request.header("Authorization", "Basic " + yourToken);

According to your answer you should try
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("UserName", "10111");
requestParams.put("Password", "123568");
request.header("Content-Type", "application/json");
request.header("Authorization", "Basic " + base64encodedToken); //This is the important line
request.body(requestParams.toString());
Response response = request.post("/entrepreneur/consolidatedEodTrigger");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "200");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");

Related

Bad request when posting to OData Data Entity in Dynamics 365

I've created a public Data Entity in dynamics with the following fields:
I keep getting a bad request response, but I'm not sure why.
I've tried to make a POST request in two ways:
1.
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionStatus = "Created" };
string jsonMessage = JsonConvert.SerializeObject(hireAction);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "MyDynamicsEnvironmentName/data/HireActions?cross-company=true");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("Authorization", AuthResult.AuthorizationHeader);
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Logic
}
}
var url = "MyDynamicsEnvironmentName/data/HireActions?cross-company=true";
var req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers["Authorization"] = AuthResult.AuthorizationHeader;
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionId = "12345", HireActionStatus = "Created" };
var jsonSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var postString = "CompanyName='DEMF'" + "&MovieId='DEMF-000000014'" + "&HireActionId=132&HireActionStatus='Created'";
var data = JsonConvert.SerializeObject(postString, jsonSettings);
var bytes = Encoding.Default.GetBytes(postString);
var newStream = req.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
using (var resp = req.GetResponse())
{
var results = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
Some keypoints:
-Of course you'd replace MyDynamicsEnvironmentName with the URL for the environment. The URL is correct and verified however, by the fact that GET requests do work
-The Authresult.AuthorizationHeader contains a valid token, also validated by working GET requests
As said before, both of these result in a bad request. Does someone know what is wrong or missing?

Transition JIRA issue via API returning a 400

I'm trying to transition issues via the API using .NET but I'm consistently getting a 400 error back. I'm wondering if anyone can see anything obvious that I'm doing wrong?
Code:
string example = #"{
""id"": ""221""
}";
string ticketjson = JsonConvert.SerializeObject(example);
string postUrl = "https://myurl/rest/api/2/issue/" + issueKey + "/transitions";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:pwd");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(ticketjson, Encoding.UTF8, "application/json");
var response = client.PostAsync(postUrl, content).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
else
{
unauth.Text = "There has been a problem submitting your comment. Please try again.";
return response.StatusCode.ToString();
}
The transition exists and when I go to the postUrl I can see it:
Any help would be appreciated!

Using RestAssured, I am getting a partial response. not sure what exactly am I missing

Request being sent:
'''#Test
public void firstPost() {
RestAssured.baseURI = "https://reqres.in/";
JSONObject reqBody = new JSONObject();
reqBody.put("name", "Ajay");
reqBody.put("job", "leader");
RequestSpecification reqSpec = RestAssured.given()
.body(reqBody);
Response res = reqSpec.post("/api/users");
System.out.println(res.asString());
}'''
Response being printed is:
{"id":"403","createdAt":"2020-08-28T18:13:32.294Z"}
Expected response
{
"name": "Ajay",
"job": "leader",
"id": "403",
"createdAt": "2020-08-28T18:13:32.294Z"
}
You should add contentType like below.
#Test
public void firstPost() {
RestAssured.baseURI = "https://reqres.in/";
JSONObject reqBody = new JSONObject();
reqBody.put("name", "Ajay");
reqBody.put("job", "leader");
RequestSpecification reqSpec = RestAssured.given()
.contentType("application/json") // <-- add this
.body(reqBody);
Response res = reqSpec.post("/api/users");
System.out.println(res.asString());
}
See the official wiki for more info about Content Type

Oauth2 Yahoo Gemini API

I am having trouble calling Yahoo Gemini API to access Yahoo Gemini Advertising from my C# console (desktop) application.
Here are steps I used:
Create an installed application on https://developer.yahoo.com/apps/create/. This gave me both {Client ID} and {Client Secret}.
https://api.login.yahoo.com/oauth2/request_auth?client_id={Client ID} &redirect_uri=oob&response_type=code&language=en-us. This will take me to the yahoo login screen where I sign in. Press the Agree button and the next screen shows the seven-letter authorization code (say nzbcns9). I write down this authorization code.
Then I use the following code to try to get the access token:
class Program
{
static void Main(string[] args)
{
string clientId = {Client ID};
string secret = {Client Secret};
var request = WebRequest.Create(#"https://api.login.yahoo.com/oauth2/get_token");
request.Method = "POST";
SetBasicAuthHeader(request, clientId, secret);
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
request.ContentType = "application/x-www-form-urlencoded";
var response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
}
static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
}
Then I get
Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse().
What did I do wrong?
I also try to post the same message using Fiddler, I get
{"error":"invalid_request"}
I tried your code and what worked for me was to put the line request.ContentType = "application/x-www-form-urlencoded"; BEFORE Stream dataStream = request.GetRequestStream();
So this worked:
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
Neither of these worked for me, but it did work once I changed the SetBasicAuthHeader to use ISO-8859-1 encoding:
static void SetBasicAuthHeader( WebRequest request, String userName, String userPassword )
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String( Encoding.GetEncoding( "ISO-8859-1" ).GetBytes( authInfo ) );
request.Headers[ "Authorization" ] = "Basic " + authInfo;
}

Using twitter to get bearer token

I'm using the following code to return the bearer token but i keep getting
"The remote server returned an error: (500) internal server error" on line
"WebResponse response = request.GetResponse();"
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");
string consumerKey = "31111111111111111111";
string consumerSecret = "1111111111111111111111A";
string consumerKeyAndSecret = String.Format("{0}:{1}", consumerKey, consumerSecret);
request.Method = "POST";
request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.Unicode.GetBytes(consumerKeyAndSecret))));
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Any advise would be amazing
I found the solution after wasting many hours.
This error will rise because of the base64 encoding using Unicode. Just change the UNICODE to UTF8, and nothing else.
Final code:
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");
string consumerKey = "31111111111111111111";
string consumerSecret = "1111111111111111111111A";
string consumerKeyAndSecret = String.Format("{0}:{1}", consumerKey, consumerSecret);
request.Method = "POST";
request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKeyAndSecret))));
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
In the past I have used TweetSharp that uses Twitter's 1.1 API. You'd probably be better using that for your twitter calls.
TweetSharp Github: https://github.com/danielcrenna/tweetsharp
If you require an example or what you need, let me know.

Resources