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

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}

Related

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

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

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:

Set HTTP Header value in rest api using Groovy in SOAP UI

I have a REST API project in SOAP UI which contains 20 test cases in a test suite. I want to add some header value and sslkeystore in every test step. Here is my code.
import com.eviware.soapui.support.types.StringToStringMap
testCaseList = testSuite.getTestCases()
testCaseList.each
{
testCase = testSuite.getTestCaseByName(it.key)
restTestSteps = testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep)//only RestTestRequest steps
restTestSteps.each
{
it.getRestRequest().setHttpHeader("TEST2")
it.testRequest.setSslKeystore("**************")
}
}
Above code "TEST2" contains the header value that I want to add to every test cases. I have configured TEST2 in ws-security configuration under outgoing ws-security configuration.
But in above code I am getting following error:
groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.getRestRequest() is applicable for argument types: () values: [] Possible solutions: getTestRequest(), getHttpRequest()
Anybody help me please how can I add header value in every test steps.
If you want to set the header values for each step in a test case, you can create a groovy test step that will do this. Place the groovy step at the beginning of the test case and it will work even if you change or add new steps. I'm sure you could tweak the getAllHttpSteps to include all test cases in the suite as well, and place this as the first test run.
/**
* This script populates all http requests in a test case with headers:
*/
import com.eviware.soapui.support.types.StringToStringMap
// make a list of all http rest requests
getAllHttpSteps=testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep)
// iterate through the list of requests and populate the request headers
for (step in getAllHttpSteps)
{
def headers = new StringToStringMap()
headers.put("SomeHeader", "SomeHeaderValue")
headers.put("sslKeystore", "keystoreValue")
}
If you want to add header value and sslkeystore in every test step, then add these values as Properties OR Custom Properties in Project. Then assign these values in each step. Are you willing to do this with groovy script?

How do I add a field for a header for an authentication token for Swagger UI?

My team has just started creating RESTful services for data that has previously been handled by a large monolithic legacy application. We want to document the api with Swagger UI and I have set up with one problem.
I need to pass a SAML token as a header parameter, otherwise when we try to click on the "Try it out!" button I get a 401 Authentication error. How do I add a field to the Swagger UI so that someone can put a String for a SAML token to be sent in the request?
This is actually really easy. I saw references to the answer in the documentation but I didn't really understand what it was saying. There is a field at the top next to where your service URL goes and you can use that field to input a string to pass as a header value. That input field has an id of #input_apiKey.
Then in the index.html file you just add a line to the addApiKeyAuthorization() javascript function telling it to take the value of that field and pass it as whatever value you need.
Example:
function addApiKeyAuthorization(){
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
swaggerUi.api.clientAuthorizations.add("samlToken", new SwaggerClient.ApiKeyAuthorization("samlToken", key, "header"));
swaggerUi.api.clientAuthorizations.add("Content-Type", new SwaggerClient.ApiKeyAuthorization("Content-Type", "application/json", "header"));
swaggerUi.api.clientAuthorizations.add("Accept", new SwaggerClient.ApiKeyAuthorization("Accept", "application/json", "header"));
}
}
$('#input_apiKey').change(addApiKeyAuthorization);
This sets the Content-Type and Accept headers to the same values for every request, and takes the value in that input field at the top of the page in the green header and sets it as my SAML token. So now if I paste in a valid SAML string my request works and I get data back!

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