Get auth token in Gatling - gatling

I'm trying to use Gatling to test my API but I've got a problem. I'm testing for now the login/logout. At the login, the user got a token, that is used for logout.
When I use the recorder, it keep a fix token, and of course, it doesn't work when I run the test. But I don't find in the doc or google how I can get dynamically the token.
Does anyone know ?
Thanks !
EDIT:
after recording here what I got
val headers_13 = Map(
"Accept" -> """*/*""",
"Origin" -> """http://site.com""",
"token" -> """token"""
)
val scn = scenario("Scenario Name")
.exec(http("request_1")
.post("http://site.com/login")
.headers(headers_1)
.param("""player[email]""", """email#address.com""")
.param("""player[password]""", """password""")
)
.pause(757 milliseconds)
…
.exec(http("request_13")
.get("http://site.com/logout")
.headers(headers_13)
)
.pause(202 milliseconds)
I try to put the two pieces of code after .post("http://site.com/login") and .get("http://site.com/logout") but that didn't works

Where is your token? Is it a HTTP header?
Generally speaking, the way to save data from responses in order to reuse it for further requests is the Check API.
.check(header("tokenName").saveAs("token")
...
.header("tokenName", "${token}")

Related

Use token obtained using R package AzureAuth to Query data

I am using the following code to get an access token using AzureAuth package in R
library (AzureAuth)
AuthToken <- get_azure_token("120d688d-1518-4cf7-bd38-182f158850b6",tenant="72f988bf-86f1-41af-91ab-2d7cd011db47", app="1950a258-227b-4e31-a9cf-717495945fc2");
However, I don't see any examples on how to use the obtained AuthToken in query data from an API?
Appreciate any help!
Pls point out my mistake if I misunderstand your question.
=======================Update=======================
Yes, I found some documents and I followed the sample. And I found that, if I wanna to call graph api, I just need to 'install.packages("AzureGraph")', and with this package I can reach my goal. And if I need to use AzureR to do some other operations on azure, the ducoment above has offered an example to illustrate how to create a resource group and storage account in AzureRMR, and a registered app in AzureGraph.
===================================================
Getting started with httr
I use this code to get httr get request, and http post request is similar, look up the document above for more details:
a <- GET("https://graph.microsoft.com/v1.0/me", add_headers(Authorization = "Bearer <accesstoken>"))
I just figured out the syntax. I found it difficult on two counts
Syntax for POST command. There are lot of examples for GET command but not many on POST
Getting to access_token. However once I started using R Studio, I was able to inspect the object and find the right field. Here is the syntax that worked for me
res <- POST(EnvironmentFqdnUrl,add_headers(Authorization = paste("Bearer", AuthToken$credentials$access_token)), body = upload_file("body.json"), verbose())
print(res)

How to take value of a variable in Gatling script

I have extracted token value from the login api call.but i am not able to use that variable value into next api call.My code is given below
val scn = scenario("test login")
.exec(http("login call")
.post("https://api.k6.io/v3/account/login")
.headers(headers_1)
.body(RawFileBody("data/login.json"))
.check(status.is(200))
.check(jsonPath("$.token.key").saveAs("tokenId")))
.pause(21)
.exec(http("edit profile call")
.post("https://api.k6.io/v3/users/3187878")
.headers(headers_1)
.header("Authorization", "Token ${tokenId}")
.body(RawFileBody("data/editprofile.json"))
.check(status.is(200)))
but the call get failed. I am not getting the value of that variable in the second call.
{"key":"4c713e3f5d362f0002f6eef737401e249c154bed"}
i need to use the value of 'key' in the header for next api call as in the format of
.header("Authorization", "Token 4c713e3f5d362f0002f6eef737401e249c154bed")
but it is not getting in this format.where i am going wrong?Can anyone help me.Thanks in advance
Your way of capturing data with a check and re-injecting it with Gatling Expression Language is correct.
Possible reasons your scenario doesn't work:
the "login call" request fails and is not able to capture the data
you use RawFileBody but maybe some data in there needs to be dynamic, just like your Authorization header
If you want to check what's been captured, you can add an extra action before your pause:
.exec { session =>
println(session("tokenId").as[String])
session
}

Quickbooks Authorization error

i have got Access token from "https://oauth.intuit.com/oauth/v1/get_request_token" using rest api in apex. when i pass the response to the authorizaiton url as shown below
https://appcenter.intuit.com/Connect/Begin?oauth_token_secret=xEtlEPu7ljKAeWRYM6pZwY02e8ewZcZ2txR1xpix&oauth_callback_confirmed=true&oauth_token=qyprdc5t2G9j8TcR8AW1123BCD3iy4M0PSBwsk84Rl8WhmCa
i get this error
Oops! An error has occurred.
Please close this window and try again.
Error Code: no_such_database
Message: Application not found by appToken
Any kind of help will be much appriciable
I am not sure if you figured it out but the URL for authorization actually seems different from documentation :
https://appcenter.intuit.com/Account/DataSharing/Authorize?oauth_token=YYYY
I used this url for authorization and it worked.
Instead of old user authorization link (https://appcenter.intuit.com/Connect/Begin ) use the new link (https://appcenter.intuit.com/Account/DataSharing/Authorize)
After generating the request token and secret , redirect to the new link. This will lead to the user authorization pages. Once authorized it will redirect back to our callback url.
Code Example :
$userAuthUrl = "https://appcenter.intuit.com/Account/DataSharing/Authorize";
$signedUrl = "{$userAuthUrl}?oauth_callback={$callBackUrl}&oauth_consumer_key={$consumerKey}&oauth_nonce={$nonce_random}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={$timestamp}&oauth_token={$reqToken}&oauth_version=1.0&oauth_signature={$signature}";
header("Location:$signedUrl");
Authorized URL is not correct.
It should be like -
https://appcenter.intuit.com/connect/begin?oauth_token=qyprdsGhfVztCxWPDIXbPYjVybkwxNAvUdNNaiaTabcde
Here oauth_token is actually request_token (not request_secret) which you get as part of the first call OAuth1.0a flow.
ie. https://oauth.intuit.com/oauth/v1/get_request_token
Please refer this sample Java code which shows all the 3 steps required to generate accessToken and accessSecret (OAuth1.0a).
https://gist.github.com/manas-mukh/b6450bb28506e1302463

PUT/GET with Payload using Restangular

I am using Restangular in one of my works
The server guys have give me the following calls which i need to integrate on the AngularJS client
PUT api/partners/password – RequestPayload[{password,confirmpassword}]
partner id is being sent in the header
GET api/partners/password/forgot/ - Request Payload [{emailaddress}]
partner id is being sent in the header
The javascript code that I have written to call these services is as follow
Restangular.all('Partners').one('Password').put(params); - sends params as query string
Restangular.all('Partners').one('Password').one('Forgot').get(params); - sends object in the url
I have tried other ways but it simply doesn't make the correct call.
Help me out guys!
So, for point #1. it puts the object at hand, not another object. So you have 2 options:
Option 1
var passReq = Restangular.all('Partners').one('Password');
passReq.confirmPassword = ....
passReq.put(); // confirmPassword and the params of the object will be sent
Option 2 is
var passReq = Restangular.all('Partners').one('Password').customPUT(obj);
For Point #2, you cannot send a request body (payload) in the GET unfortunately.

Google Channel API sending message with token

In documents it says 'client_id' part can actually be the token, however it doesn't work. Anyone know why?
https://developers.google.com/appengine/docs/python/channel/functions
If the client_id parameter is actually a token returned by a create_channel call then send_message can be used for different versions of the app. For instance you could create the channel on the front end and then send messages from a backend of the app.
the reason i want to use this, is because i want to send messages to anonymous users as well, without requiring them to login. i don't know if it is possible to assign them a 'client_id' if token doesn't work.
this is how i am creating the token
user = users.get_current_user()
if user:
token = channel.create_channel(user.user_id())
else:
token = channel.create_channel(str(uuid.uuid4()))
then injecting into client
template_values = {
'token' : token,
}
on the client side open the channel
openChannel = function() {
var token = '{{ token }}';
var channel = new goog.appengine.Channel(token);
var handler = {
'onopen': onOpened,
'onmessage': onMessage,
'onerror': function() {},
'onclose': function() {}
};
var socket = channel.open(handler);
socket.onopen = onOpened;
socket.onmessage = onMessage;
}
now send a message
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send();
in the server,
when the message is received send back a message using the token
channel.send_message(token, someMessage)
back to client
onMessage = function(m) {
alert("you have some message");
}
this sequence works fine if client_id() is used instead of token when calling send_message
In response to btevfik's initial question: Allowing tokens or client_id in send_message is a feature released in 1.7.5 (very recently). Some people may not be familiar with it yet so therefore they suggest to use client_id. Both should work!
The only thing that I can see in your code is the fact that you should not rely on token variable to be correct in between two requests. They may not even land on the same instance of the app. If you share your code with more details I may be able to spot something. The proper way would be to either store the token in the datastore or pass it from the client as a parameter when you send the message that will trigger a message back.
The purpose of this feature was to allow people to send messages from backends (or other versions). Before was not possible whereas now you can do it if you use directly the tokens instead of the client_id.
Long time this post has been around, but just curious about your usage of the token global variable?
I don't see this code:
global token
before you set the token
user = users.get_current_user()
if user:
token = channel.create_channel(user.user_id())
else:
token = channel.create_channel(str(uuid.uuid4()))
If that code is missing, then token will be set in the local scope of the function above and not globally. So, the token value used later will be None (or to what ever the token was initialised with.)
Just a thought, if its still relevant.
I don't think you actually have a problem here.
You are able to send messages to users that are logged in or not.
The problem you are having I think is knowing that there are multiple ways to use the channel API re: tokens.
https://developers.google.com/appengine/docs/python/channel/overview#Life_of_a_Typical_Channel_Message
In this example, it shows the JavaScript client explicitly requests a token and sends its Client ID to the server. In contrast, you could choose to design your application to inject the token into the client before the page loads in the browser, or some other implementation if preferred.
This diagram shows the creation of a channel on the server. In this
example, it shows the JavaScript client explicitly requests a token
and sends its Client ID to the server. In contrast, you could choose
to design your application to inject the token into the client before
the page loads in the browser, or some other implementation if
preferred.
Here's my demo implementation, hope it helps somehow: https://github.com/Paul1234321/channelapidemo.git
Here's the code for creating the channel on GAE:
client_id = str(uuid.uuid4()).replace("-",'')
channel_token = channel.create_channel(client_id)
And in the JS:
channel = new goog.appengine.Channel('{{ token }}');
Have a look at it in action: http://pppredictor.appspot.com/
You shouldn't store request-specific values in global variables. Store them in a cookie or pass them as a request parameter instead.

Resources