Error passing headers to Invoke-RestMethod - powershell

I have one function that obtains an OAuth 2 token and assembles a header; and others that use the header to make various requests to Microsoft Graph.
The function that assembles the header has two methods: one is interactive with a device code flow; and the other is non-interactive with a username and password flow.
Both methods produce a header that looks the same. The token object and the header object are the same types of object in both cases.
But, when the header is used in another GET function, the function fails in the interactive case and succeeds in the non-interactive case. The error is: "Cannot convert 'System.Object[]' to the type 'System.Collections.IDictionary' required by parameter 'Headers'."
The object returned by the header function is an array (object, base type: system array) in the failed case. It is a hashtable (hashtable, base type: system object) in the successful case. Even though, internally in the function, the token and the header are the same type. Token is System.Management.Automation.PSCustomObject, and header is hashtable.
The code that assembles the header is: $authHeader = #{
'Authorization' = "Bearer $( $tokenResponse.access_token)"
'Content-Type' = "application/json"
'ExpiresOn' = $( $tokenResponse.expires_in)
The access tokens are both long strings contained in the token response. They seem similar, and both decode OK at jwt.io.
Any ideas why two headers that look the same would be different object types, and how to get the failed one into an IDictionary format?

Found it. A prompt for input in the interactive authentication added an empty string to the output. Solution was to add | Out-Null to the prompt.

Related

Invoke-RestMethod Link Method not supported

I'm interfacing with an API with PowerShell Invoke-RestMethod cmdlet.
One of the API endpoints requires the method "Link", however this method is not supported by Invoke-RestMethod.
With CURL it is working fine
Is there a way around this?
Error message:
Invoke-RestMethod : Cannot bind parameter 'Method'. Cannot convert value "LINK" to type "Microsoft.PowerShell.Commands.WebRequestMethod". Error: "Unable to match the identifier name LINK to a valid enumerator name. Specify one of the following enumerator names and try again:
Default, Get, Head, Post, Put, Delete, Trace, Options, Merge, Patch
In PowerShell v6+, Invoke-WebRequest has a parameter CustomMethod.
This can be used with the Request Method required by the endpoint is not an available option on the -Method.
Look at the MS documentation on how to use custom method in invoke-webrequest
Update
You can use .Net class WebRequest to send your request as follows, and this will work on any PowerShell version:
$req = [net.webrequest]::create('https://www.google.com')
$req.Method = 'LINK'
$resp = $req.GetResponse()
Look here for further information

Dynamically determine header based on GET parameters

For one of our REST webservices, we have implemented a GET method having the following URI:
http://ourcompany.com/doSomething/getSomething?parameter1=ABC&parameter2=123
Now, one of the headers required for security is the following
userName: ABC123, derived from concatenating the values of parameter1 and parameter2
My question is, how, in SoapUI (preferably via the SoapUI interface, itself), do I dynamically generate this header value from the parameter values supplied in the GET method?
You can create test case level custom properties instead of string value for the parameters which you have currently, say
name as PROPERTY1, and value as ABC
name as PROPERTY2, and value as 123
In the GET request step, provide values as Property Expansion, say
${#TestCase#PROPERTY1}, ${#TestCase#PROPERTY2} respectively for the parameters.
Coming to the headers, define the required header and use Property Expansion again. i.e., header name as userName and value as ${#TestCase#PROPERTY1}${#TestCase#PROPERTY2}
Hope the above should resolve the issue.

Invalid_request_parameter (create and sending envelopes)

I'm trying to use a service of DocuSign API in an abap project. I want to send a document to a specific email so it can be signed. But im getting the following error:
"errorCode": "INVALID_REQUEST_PARAMETER",## "message": "The request contained at least one invalid parameter. Query parameter 'from_date' must be set to a valid DateTime, or 'envelope_ids' or 'transaction_ids' must be specified.
I tried the following:
CALL METHOD cl_http_client=>create_by_url
EXPORTING
url = l_url (https://demo.docusign.net/restapi/v2/accounts/XXXXXX')
proxy_host = co_proxy_host
proxy_service = co_proxy_service
IMPORTING
client = lo_http_client
lo_http_client->request->set_method( method = 'POST').
CALL METHOD lo_http_client->request->set_header_field
EXPORTING
name = 'Accept'
value = 'application/json'.
CALL METHOD lo_http_client->request->set_header_field
EXPORTING
name = 'X-DocuSign-Authentication'
value = get_auth_header( ). (json auth header)
CALL METHOD lo_http_client->request->set_cdata
EXPORTING
data = create_body( ).
This is my body:
CONCATENATE
`{`
`"emailSubject": "DocuSign REST API Quickstart Sample",`
`"emailBlurb": "Shows how to create and send an envelope from a document.",`
`"recipients": {`
`"signers": [{`
`"email": "test#email",`
`"name": "test",`
`"recipientId": "1",`
`"routingOrder": "1"`
`}]`
`},`
`"documents": [{`
`"documentId": "1",`
`"name": "test.pdf",`
`"documentBase64":` `"` l_encoded_doc `"`
`}],`
`"status": "sent"`
`}` INTO re_data.
The api request to get the Baseurl is working fine. (I know the error is quite specific what the problem is, but i cant find any sources on the docusign api documentation that one of the mentioned parameters should be added to the request)
Thank you in regards
The error message seems to indicate that you're Posting to an endpoint that requires certain query string parameters -- but you're not specifying them as expected in the query string. I'd suggest you check the DocuSign API documentation for the operation you are using, to determine what query string parameters it requires, and then ensure that you're including those parameters in your request URL.
If you can't figure this out using the documentation, then I'd suggest that you update your post to clarify exactly what URL (endpoint) you are using for the request, including any querystring parameters you're specifying in the URL. You can put fake values for things like Account ID, of course -- we just need to see the endpoint you are calling, and what qs params you're sending.
To create an envelope, use
https://demo.docusign.net/restapi/v2/accounts/XXXXXX/envelopes
instead of
https://demo.docusign.net/restapi/v2/accounts/XXXXXX
Thank you for all the answers, i found the mistake. Creating the request wasn´t the problem. I was using the wrong "sending"-method -_-.
now its working :)
lo_rest_client->post( EXPORTING io_entity = lo_request_entity ).

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!

Sign in to twitter via PowerShell

I'm experimenting with PowerShell and got following problem:
When I wanted to sign in to twitter using Invoke-WebRequest
$r = Invoke-WebRequest -Uri "http://www.twitter.com"
$r.Forms[1].Fields.session[username_or_email] = "user"
$r.Forms[1].Fields.session[password] = "password"
and tried to assign a value to request object, it was impossible because of the twitter naming convention of their fields. This is what I got as an error message
Unexpected token 'username_or_email]' in expression or statement.
Is there some simple way to escape this characters?
The name of the field is session[username_or_email] and in PowerShell you have two ways of referring to that:
# dot notation, but it must be quoted because of special characters
$r[1].Fields."session[username_or_email]"
# array notation, must be quoted either way
$r[1].Fields["session[username_or_email]"]
Normally you could have just done $r[1].Fields.TheFieldName but you have to put it in quotes because of the special characters involved.
Additionally, I will point out that the response in $r should have already parsed all the fields into the object, letting you tab complete them, but this object does a strange thing: if an <input> field has an id attribute, it will name the object based on that instead of the name, which is why you'll find a field called signin-email but not one already named session[username_or_email].
If it causes you issues when you submit, you may want to manually remove the id-based fields.