Robot Framework api test with Oauth2 - pass generated token to other test cases - rest

Using similar code to this one, I am able to successfully generate a Token and authorize the request bellow it. Both actions happen in one test case. I tried creating a new test case with only copying the second request code and of course it says unauthorized.
So my question is, since I can generate a token in the first test case, what do I have to add in order to use/pass the already generated token for a second, third, fourth, test cases?
${data}= Create Dictionary Token_Name=TestTokenname grant_type=<grant type> client_Id=<your Id> Client_Secret=<Your client secret> scope=<your scpe>
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= RequestsLibrary.Post Request OA2 identity/connect/token data=${data} headers=${headers}
BuiltIn.Log To Console ${resp}
BuiltIn.Log To Console ${resp.status_code}
Should Be Equal As Strings ${resp.status_code} 200
Dictionary Should Contain Value ${resp.json()} Testtokenname
${accessToken}= evaluate $resp.json().get("access_token")
BuiltIn.Log to Console ${accessToken}
${token}= catenate Bearer ${accessToken}
BuiltIn.Log to Console ${token}
${headers1}= Create Dictionary Authorization=${token}
RequestsLibrary.Create Session GT <Your Server URL> verify=${True}
${resp}= RequestsLibrary.Get Request GT <Your API URL> headers=${headers1}
Should Be Equal As Strings ${resp.status_code} 200 ```

In your code, after getting and storing token in a variable, add the below line of code immediately. Variables set with this keyword are globally available in all subsequent test suites, test cases and user keywords.
Set Global Variable ${token}
More detailed explanation in the below link
https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Global%20Variable

Related

Extract response output from one api and needs to be passed in the 2nd

This is my response:
{"token":"eyJ0eXAiOiJKV1QiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiUlNBMV81In0.ezPR0PlML3xO08dEYnJO2QfW8wLc9Hbju1wSqBGM0MEC_YUmsOzQH9X_KvVAH0si7xUVrH74IcLcOlkqGBB5x1ZWQHzh_Zn3ej1JS_n55iXqK1bcOn2dGYjr-yTbIRzxAtUYy8FoV3aEPHwGHh6Ehc3AgOgSSq69ep4CcAUZ38Ga65cd-Aei7dfXMMqtYpHksj6K2TJ3EpFPqqZTfwmLnSomQiWNBC5u6Adkjra5zcQWNRsE2ghcaNQGtMURwjZzeNo4wMWewt1K7CobzS9JPNscK_taOIIhV3vljAf_mRkU7imujdXhchErXoTLD6-cq15txh7xJeo9o1cIm2RDLQ.UCfbgjMC5WsOf_kJsPnQOg.tfvajQljduDdtzwaWaKVxEjr4iEUeo72nS-vag6J35UIdUxdqrQYBixeKjw3vidLN7md2qNRR3fuhzejpkV05DXfyU-bDLa17wn42Ad9L5mId9mNrF9E5oVOGfnrNuoACtCgUp7ntJFBrlhzfNBXJa6AcTOrMSIX5pkXuU4ULhjFw92DqPShbUKCFQFl8UHCmU5u6263t5sSeZmwhmU65fwUeFNnbrMMePYKvRhAOEqe88djreX2j4ErAhBaDQNWVmijtqh32LFHvm_WVX8BmfY5T5-0rfMmRqZXNgesDNEdQRp1FqnSKe9rk22j4DM3y3UiXiMdS2U6eEVD_aeeQZUAqTfS7Q-cWJAxxWQLkrqeMrbLPFD6tfvac_4NQ1sgOG-CNaszkR-_0cwV1c9udQ.9FtyIM8BlR7sQXnO2ILV0CVuhiOy7oxZ8Aol2niJae9apU5T6ff5pynLqsmf6zx1fACne9vW7eNhKfup2LZWUg", "loggedInUserName": "usadm002", "loggedIndomain": "gisus"}
I need to extract token and use in 2nd API
Use JSON Extractor Postprocessor for this purpose. Add the JSON extractor element to the request which returns the above-mentioned response. Then configure it as below:
Name of the created variables: TOKEN (Any name)
JSON Path Expressions: .token
Default Values: NOT_FOUND (The Custom value you want to see by default)
Then you can use the variable in your subsequent requests as ${TOKEN}

Using OAuth2 how do I pull the access token into a variable?

I am trying to make a call to an authorization endpoint using OAuth2 with grant type Client Credentials - my call is successful - that is not an issue. However, I, now, want to take the access token that is returned and put it in a variable so I may use it in subsequent calls without having to manually cut-and-paste to my other calls.
When the call returns I see the token I desire to copy in the Access Token field at the bottom of the OAuth2 window (the one shown below that says expires in 42 minutes) AND I see it in the Authorization field on the Timeline tab of the results. I just can't figure out how to get access to it so I may dump it into variable.
The gif on the FAQ goes really fast, and does not provide step by step. Also, I didnt find any answer on YouTube or other websites, so I thought to share step by step for chaining requests on Insomnia.
Create a POST query to obtain your access token. Notice that my access token is returned in the field called "access_token", we will use this in step 3. Your return field may be different.
Create a second GET request for the API that would return the data for you. In my case, I wanted to get all users from a SCIM interface. In the Bearer tab, type in Response => Body Attribute (Insomnia will autofill).
Mouse click on the Request => Body Attribute (the one you just typed in), and select the authentication post in the dropdown "Request" (this is the one you created in step 1), and in the "Filter (JSONPath)" field, type in the $.[attribute name] - where attribute name is the response that returns from authentication call. In my case, it was access_token, see step 1 for yours.
Enjoy!!
Click No Environment > Manage Environments and you will see a base environment in JSON.
Since this is in JSON, create a { "jwt_token": "Response => Body Attribute" }" pair for your token variable. Please note that "Response => Body Attribute" needs to be configured. When you type response, hit space and this option should be available.
Once done choosing "Response => Body Attribute", it will show with some gibberish content and with red background, no worries... just click it to configure. Make sure you have the same setup.
However... you need to change your request to the route where you get the token from the server and another thing is the Filter (JSONPath or XPath) change it depending on your setup.
You should have the token, stored in jwt_token variable and can use the variable on a route that you like.
Example:
If you want to save a token that is returned in a response into an environment variable, you can use request chaining in your environment variable. Take a look at this url for more details on that https://support.insomnia.rest/article/43-chaining-requests...
Here is what you could do (what I did)
Create an environment variable
For the value of the variable, use the Response => Body Attribute and under Filter (JSONPath or XPath), choose the attribute of the token in your response body (if it is "token" then put $.token).
After that just put the token environment variable wherever you need it in the following requests.
I was not able to resolve this question but was able to get around it by defining the fields in the body of the request and bypassing the OAuth2 tab completely.
You can add it as a header, by referencing the outputs of the OAuth2 request:

How to automate dynamic token generated by a URL for Rest API in SOAPUI?

For my project
I have created test cases in SOAPUI for Rest project.
I have to pass token in header for each test steps that I have added in the test cases.
Also the token validity only for 1 hour. So every hour I have to enter the token in the headers.
I want to know is there any way automate this token entry and generation dynamically ?
For now what I am doing is getting token every time by refreshing the URL in every 1 hour and putting it manually in header of every test case and test steps.
You could use something like the following Groovy script as the first test step of your test case. This gets your authorisation token from whatever service you use and sets it in your request header:
def authorisationToken = // Retrieve a new token from your authorisation service
// Get the headers for the request
def restRequest = testRunner.testCase.getTestStepByName('REST request')
def headers = restRequest.httpRequest.requestHeaders
// Set the token as a header. Remove it first in case it already exists
headers.remove("Authorisation") // Or whatever your header is called
headers.put("Authorisation", authorisationToken)
restRequest.httpRequest.requestHeaders = headers
If you need to, you could also create a custom property at, say, the test suite level, then set this property after you retrieve it:
testRunner.testCase.testSuite.project.setPropertyValue("Authorization", authorisationToken)
Then, you could use it anywhere you need with ${#TestSuite#authorisationToken}

what API Gateway methods support Authorization?

When I create a resource/method in AWS API Gateway API I can create one of the following methods: DELETE, GET, HEAD, OPTIONS, PATCH or POST.
If I choose GET then API Gateway doesn't pass authentication details; but for POST it does.
For GET should I be adding the cognito credentials to the URL of my GET? or just never use GET and use POST for all authenticated calls?
My set-up in API Gateway/Lambda:
I created a Resource and two methods: GET and POST
Under Authorization Settings I set Authorization to AWS_AIM
For this example there is no Request Model
Under Method Execution I set Integration type to Lambda Function and I check Invoke with caller credentials (I also set Lambda Region and Lambda Function)
I leave Credentials cache unchecked.
For Body Mapping Templates, I set Content-Type to `application/json' and the Mapping Template to
{ "identity" : "$input.params('identity')"}
In my Python Lambda function:
def lambda_handler(event, context):
print context.identity
print context.identity.cognito_identity_id
return True
Running the Python function:
For the GET context.identity is None
For the POST context.identity has a value and context.identity.cognito_identity_id has the correct value.
As mentioned in comments: all HTTP methods support authentication. If the method is configured to require authentication, authentication results should be included in the context for you to access via mapping templates to pass down stream as contextual information.
If this is not working for you, please update your question to reflect:
How your API methods are configured.
What your mapping template is.
What results you see in testing.
UPDATE
The code in your lambda function is checking the context of the Lambda function, not the value from API Gateway. To access the value passed in from API Gateway, you would need to use event.identity not context.identity.
This would only half solve your problem as you are not using the correct value to access the identity in API gateway. That would be $context.identity.cognitoIdentityId (assuming you are using Amazon Cognito auth). Please see the mapping template reference for a full guide of supported variables.
Finally, you may want to consider using the template referenced in this question.

SoapUI 5.0 Create cookie

I'm trying to run a REST project and have inserted securitytoken and session into my header.
But I get an errormessage telling me that a cookie is missing (since my service needs a cookie to run successful).
I have tried to do this with Groovy:
import com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport
def myCookieStore = HttpClientSupport.getHttpClient().getCookieStore()
import org.apache.http.impl.cookie.BasicClientCookie
def myNewCookie = new BasicClientCookie("mycookiename", "mycookievalue")
myNewCookie.version = 1
myNewCookie.domain = "my domain as IP"
myCookieStore.addCookie(myNewCookie)
But its still throwing me the same errormessage.
Are there any solution to inject a cookie as a header in SoapUI 5.0?
I would have like to add this as a comment, but I don't have 50 reputation yet.
Don't know if you are still working on this, but anyway:
Like Rao says it seems like you want to work in a session with a negotiated token. You can go three ways with this in soapui.
Like you propose: create the cookie and the values from scratch. That would be a good use case when you want to test which values are going to pass and which values or combos thereof will return errors or different kinds of messages.
If you want to test anything else then the headers, then you can load a certificate, go to the authentication link and retrieve your tokens and session IDs from the headers in the Set-Cookies as proposed by Rao.
Option number three, my personal favourite when testing other things than headers, is to trust SoapUI to take care of it. You can do this by setting the test case to remember your session. You can set this setting in the testcase settings menu. It is called something the likes of 'Maintain http session'.
Remark: In soapui you can modularize tests. You could for example make a testcase for the authentication in an 'util' test suite. This because you can then disable the util test suite to prevent it from running as a dead-weight test. You can then call to this testcase anywhere to invoke the authentication procedure. For this to work you have to set the settings for the 'Run Testcase' (it is named somehting like that) to 'transport the http session to and from this test case' and, like before, set the parent testcase to 'Maintain HTTP Session'. More info on modularization: https://www.soapui.org/functional-testing/modularizing-your-tests.html.
For the security certificate import, check this smartbear example: https://www.soapui.org/resources/blog/ws-security-settings.html