How do I pass the email in alias header and obtain specific responses? - rest-assured

*New to Rest Assured
Question:
How do I pass the email (User email required for GET endpoint) in the alias header and obtain the session ID as well as the username ID from the response?
Details:
The [GET] users/signin endpoint requires a user email and an api key.
Curl:
curl -X GET "https://SomeWebSite.com/apiservice/users/signin?challengeMethod=EMAIL" -H "accept: application/json" -H "alias: usersignin#EXAMPLE.com" -H "X-API-KEY: d5a1d56d51d651d651d51d651d6d6d1"
Response:
{
"session": "ID inside of here",
"challengename": "CUSTOM_CHALLENGE",
"challengeSentTo": "usersignin#EXAMPLE.com",
"username": "5d654d6d65dd64d66adsb6a4"
}
My code:
public class AuthResponseTest {
public static final String baseUri = "https://qa-mobile-app-auth-ext.clearcollateral.com/";
public static final String basePath = "/apiservice/users ";
public String[] getSignIn() {
return RestAssured
.with()
.log().all()
.header("X-API-KEY", "API KEY IN HERE")
.header("alias", "email here")
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.baseUri(baseUri)
.basePath(basePath)
.when()
.post("/users/signin")
.then()
.log().all()
.statusCode(200)
.extract().as(String[].class);
}
#Test
public void testSignIn() {
String[] authsignin = getSignIn();
System.out.println(authsignin);
}
}

Try;
.header("alias", "usersignin#EXAMPLE.com")

Related

Swagger: Authorization token is not passed into requests headers

i use springfox 2.9.2
I have api like:
#Api(tags = "Users")
#RestController
#RequestMapping("users")
public class UsersController {
#ApiOperation(value = "Creates a user")
#ApiResponses(value = {
#ApiResponse(code = 201, message = "user created"),
#ApiResponse(code = 401, message = "not authorized")})
#PostMapping(value = "/add")
public ResponseEntity addUser(#Valid #RequestBody UserDTO userDTO) {
...
}
to make this call user needs authorization token
Authorization: Bearer {token}
witch comes from authentication server.
i try to make first call to this server in swagger and pass it to controller requests like the one above.
So i do
#Bean
public Docket api() {
final String swaggerToken = "";
return new Docket(DocumentationType.SWAGGER_2)
#Bean
public .select()
.apis(RequestHandlerSelectors.basePackage("com.mbv.coros.notification.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiEndPointsInfo())
.securitySchemes(Arrays.asList(securityScheme()))
.securityContexts(Arrays.asList(securityContext()))
.useDefaultResponseMessages(false);
}
private SecurityScheme securityScheme() {
GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(AUTH_SERVER + "/token");
SecurityScheme oauth = new OAuthBuilder().name("spring_oauth")
.grantTypes(Arrays.asList(grantType))
.scopes(Arrays.asList(scopes()))
.build();
return oauth;
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(
new SecurityReference("JWT", authorizationScopes));
}
on Swagger ui authorization call returns the token successfully but it doesnt add it to request headers. It generates
curl -X GET "http://localhost:8080/users/get" -H "accept: */*"
if i set token like:
.securitySchemes(Arrays.asList(apiKey()))
private ApiKey apiKey() {
return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
}
it works perfectly.
any ideas why is this happening?
As far as I know, Swagger uses token only if you configure it to do so, and the configuration is done using the "Authorize" button on the top right of the Swagger UI page.
So, the ideal case would be:
Trigger Auth call which returns the token
Copy the token; Click on "Authorize" button and paste the JWT token in "Bearer "
After this, all the subsequent calls are supposed to use this token until you press logout.

Handle incoming call from twilio in ASP.NET WebApi

I have an existing WebApi that i want to handle incoming twilio calls.
I used this tutorial(https://www.twilio.com/docs/voice/tutorials/how-to-respond-to-incoming-phone-calls-csharp) and created a sample controller that I've attached to my existing project.
Controller:
using System.Web.Http;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;
namespace SS.RestServer.Controllers
{
public class VoiceController : TwilioController
{
[HttpPost]
public TwiMLResult Index(Twilio.AspNet.Common.VoiceRequest request)
{
var response = new MessagingResponse();
response.Message("Hello World");
return TwiML(response);
}
}
}
but when i call it like this:
http://localhost:XXXXX/Voice
I get 404
Is there a way to return TwiML MessagingResponse without inheriting from TwillioController? this way i dont need to maintain complex routing in my WebAPI
I tried to do the following:
public class VoiceController : ApiController
{
[HttpPost]
[Route("api/IncomingTwilioVoice")]
public IHttpActionResult IncomingTwilioVoice(Twilio.AspNet.Common.VoiceRequest request)
{
var response = new MessagingResponse();
response.Message("Hello World");
return Ok(response.ToString());
}
}
and got this in response:
<?xml version="1.0" encoding="utf-8"?>
<Response>
<Message>Hello World</Message>
</Response>
but when i call twilio number and it goes to this endpoint i only hear "we are sorry, application error has occurred"
Update: I made some progress, when i changed 'content-type' header in response to 'text/xml' now it just hangs up without telling me about the error...
Update:
this is what i tried next:
[HttpPost]
[Route("api/IncomingTwilioVoice")]
public TwiMLResult IncomingTwilioVoice(Twilio.AspNet.Common.VoiceRequest request) //TwiMLResult, IHttpActionResult, HttpResponseMessage
{
var response = new VoiceResponse();
response.Say("hello world!", voice: "alice");
return new TwiMLResult(response);
}
and my result is:
{
"Data": {
"?xml": {
"#version": "1.0",
"#encoding": "utf-8"
},
"#text": "\n",
"Response": {
"#text": [
"\n ",
"\n"
],
"Say": {
"#voice": "alice",
"#text": "hello world!"
}
}
}
}
but still "sorry, an application error has occured"

Thingsboard - Authentication error on REST API (FROM Curl command and ASP.NET)

I'm able to login to Thingsboard website using my credentials, however when I try to connect the same using CURL command I get "Authentication Failed" error.
curl -X POST "https://cloud.thingsboard.io/api/auth/login" -d "{"username":"XYZPQR#ABCDLMN.com", "password":"Q#34&pwn"}" --header "Content-Type: application/json" --header "Accept: application/json"
Error Code
{"status":401,"message":"Authentication failed","errorCode":10,"timestamp":1542893993515}
However when I use the same user id and Password in my ASP.NET Application to fetch the authorization token, I do get the JWT token, but using the same token I'm unable to make any REST API call from Thingsboard.
ASP.NET CORE CODE
var response = new HttpResponseMessage();
var client = new HttpClient();
UserModel model = new UserModel { username = "XYZPQR#ABCDLMN.com", password = "Q#34&pwn" };
var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
response = await client.PostAsync("https://cloud.thingsboard.io/api/auth/login", content);
string data = await response.Content.ReadAsStringAsync();
var userToken = JsonConvert.DeserializeObject<UserToken>(data);
MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userToken.token);
Uri url = new Uri("https://cloud.thingsboard.io/api/plugins/telemetry/DEVICE/431be6e0-e8ca-11e8-9e5c-3d544ba4fdfc/values/timeseries?keys=Electricity");
response = await client.GetAsync(url);
Model Class
public class UserModel {
public string username { get; set; }
public string password { get; set; }
}
public class UserToken
{
public string token { get; set; }
public string refreshToken { get; set; }
}
Please suggest, how to get the telemetry values from Thingsboard REST API.
It was a small mistake I was doing; I changed old code to new code(as shown below), and everything started working as expected.
Old code
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userToken.token);
New Code
client.DefaultRequestHeaders.Add("X-Authorization", "Bearer " + userToken.token);
Thanks for support.

Send proper api call using RestSharp to getresponse.com api

I am trying to add a contact email address to a existing campaign list named- "liakat". But I am getting a response from getresponse.com saying httpStatus 400, which you can check on the attached pitures. I have added a temporary api key, so you can test it yourself too. I am following this document from getresponse.com. Anyone who can fix this issue?
Controller:
string email = "test#gmail.com";
// Test Campaign name - "pikaa"
// "pikaa" named campaign ID->ee104303
// our api key-> 948dsdfsdfs1a017a07f3c6
var client = new RestClient("https://api.getresponse.com/v3/contacts");
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
var root = new RootObject();
root.campaign = new Campaign();
root.name = "Mr Men";
root.email = "test#gmail.com";
root.campaign.campaignId = "IDss6604303";
var jsBody = new JavaScriptSerializer().Serialize(root);
request.AddHeader("X-Auth-Token", "api-key 948sdfsdfsdfsdfsdfs6");
request.AddParameter("application/x-www-form-urlencoded", "email=" + email + "&campaign=ID85104303", ParameterType.RequestBody);
var response = client.Execute(request);
Model:
public class Campaign
{
public string campaignId { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string email { get; set; }
public Campaign campaign { get; set; }
}
There is no "connection" between the Request request and the JSON Object jsBody (or root). What you're sending is a query string.
Something like
email=test#gmail.com&campaign=ID85104303
This is defined by the line:
request.AddParameter("application/x-www-form-urlencoded", "email=" + email + "&campaign=ID85104303", ParameterType.RequestBody);
If you want to send your JSON, you need to change the line to:
request.AddParameter("application/json; charset=utf-8", jsBody, ParameterType.RequestBody);
I can't tell if this will already work, but so you're at least sending the right body and you should get a successful response or at least a better error message.

POST parameters in CURL

I am attempting to use CURL to send a simple POST parameter (an int) to an ASP.NET web api controller POST method like so:
curl -d "id=1" --ntlm --user <user>:<pass> http://dev.test.local/api/test
Is this the correct way to attach data to the POST for Curl? I can contact the URL fine but it seems the parameter 'id' doesn't get passed because i get the following error returned from the server:
"The parameters dictionary contains a null entry for parameter 'id' of non-nulla
ble type 'System.Int32' for method 'System.String Post(Int32)' in 'Test.Si
te.Controllers.TestController'. An optional parameter must be a reference type,
a nullable type, or be declared as an optional parameter."
My POST method in the OrderController is as follows:
// POST api/test
public string Post(int id)
{
return "Post successful";
}
Any help is much appreciated.
Personally I would use a simple DTO and call via JSON.
route:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}",
defaults: new { }
);
controller & DTO:
[DataContract]
public class valueDto
{
[DataMember]
public int id { get; set; }
}
public class TestController : ApiController
{
// POST api/values
public string Post(valueDto value)
{
return string.Format("Post successful {0}", value.id);
}
}
Call with curl:
curl -d "{ "id": 1 }" --ntlm --user <user>:<pass> http://dev.test.local/api/test -H "Content-Type:application/json"
But
Just to follow on a little from tugberk's answer and referencing another answer and here .
When you use the FromBody attribute you will also need to send the "Content-Type" as Content-Type: application/x-www-form-urlencoded. You will also need to change the call not have the "id=1" and instead use "=1" e.g.
curl -d "=1" --ntlm --user <user>:<pass> http://dev.test.local/api/test -H "Content-Type:application/x-www-form-urlencoded"
The problem is that simple types such as int, string, etc. cannot be model-bound with the data from the message body unless you tell it explicitly as below:
public string Post([FromBody]int id)
{
return "Post successful";
}
The other solution is that you can ask these types of values from RouteData or query string.

Resources