Need to get required http post - api

I am following Huddle Api instructions to get the Access Token. I am using powershell to post the method which is as follows:
POST /token HTTP/1.1
Host: login.huddle.net
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&client_id=s6BhdRkqt&redirect_uri=MyAppServer.com/receiveAuthCode&code=i1WsRn1uB1
Powershell Command which I am using is:
$body = { '#grant_type' = 'authorization_code'; client_id = 'xxxxx';
redirect_uri = 'myAppServer.com'; code = '123abcdef' }
Invoke-WebRequest -Uri "login.huddle.com" -ContentType "application/x-www-form-urlencoded" -Method Post
This works and I get the response of "200 OK" and also shows the activation of Access Token. How would I retrieve the Access Token number. For example, I need the output as they mentioned in instruction which is:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token":"S1AV32hkKG",
"expires_in":300,
"refresh_token":"8xLOxBtZp8"
}
I think it has something to do ContentType. So I did try, "application/Json" but that was not it. Any suggestions?

You're using the wrong cmdlet. Since you mentiond getting back values for StatusCode, Content, RawContent, etc, that tells us that you're using Invoke-WebRequest. This cmdlets awesome...but not for working with APIs, which are commonly REST formatted and use JSON. IWR can handle the request but you have to dig into the $Response.Content and convert from JSON.
Instead of Invoke-WebRequest, try using Invoke-RestMethod. It's likely that you are getting the AccessCode returned, but as a JSON formatted property. Invoke-RestMethod will natively parse and convert JSON into PowerShell objects. You can just sub it in for Invoke-WebRequest and it should just work.
Invoke-RestMethod -Uri "login.huddle.com" -ContentType "application/x-www-form-urlencoded" -Method Post -body $body

If you use Invoke-RestMethod you can set the response when making the call
$response = Invoke-RestMethod -Uri "login.huddle.com" -ContentType "application/x-www-form-urlencoded" -Method Post"
then $response.access_token or $response.expires_in or $response.refresh_token

Related

Fortify API Start Scan with Default - How to send package

I am trying to use the API from https://api.emea.fortify.com/swagger/ui/index#/
called Start Scan with Default.
I cannot find any documentation to suggest how to set the post up.
This is what I have so far, but I get an error and of course I am not sending the files to scan either, so I know it is not right.
I have tried a Get request, which works so I know it is authenticated etc.
I just need to know are the parameters correctly formatted and how do I upload the actual files to scan.
POST /api/v3/releases/43579/static-scans/start-scan-with-defaults?releaseId=43579& fragNo=22& offset=22& isRemediationScan=false& notes=hello HTTP/1.1
Host: api.emea.fortify.com
Content-Type: application/json
Authorization: Bearer [TOKEN HERE]
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 57e40c1d-c99c-40a4-a79b-06ef9a678a07,8ef4ad1e-327f-4eee-b6bb-bddb21b18d50
Host: api.emea.fortify.com
accept-encoding: gzip, deflate
content-length:
Connection: keep-alive
cache-control: no-cache
Response:
{
"errors": [
{
"errorCode": null,
"message": "Unexpected error processing request"
}
]
}
UPDATE
I have found this repo on Git written in Java, which I have tried to recreate in PowerShell with no success.
https://github.com/fod-dev/fod-uploader-java
My PowerShell:
[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebRequest]::GetSystemWebProxy()
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$zipDetails = Get-Content C:\Users\patemanc\Desktop\types.zip -Encoding Byte
Write-Host $zipDetails.Length
$releaseId = "43576"
$url = "https://api.emea.fortify.com/api/v3/releases/$releaseId/static-scans/start-scan-with-defaults?"
$url += "releaseId=$releaseId"
$url += "&fragNo=-1"
$url += "&offset=0"
$url += "&isRemediationScan=false"
$url += "&notes=PowrShell Test"
$long_lived_access_token = "ENTER TOKEN HERE"
$headers = #{Authorization = "bearer:$long_lived_access_token"}
$response = Invoke-WebRequest -ContentType "application/octet-stream" -Uri $url -Method POST -Body $zipDetails -Headers $headers -UseBasicParsing
Write-Host "Here is the end"
Write-Host $response
Error Response:
79212
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:22 char:13
+ $response = Invoke-WebRequest -ContentType "application/json" -Uri $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Why postman? If you use some plugin to run it, from Jenkins for example, it works fine. I don't know how the plugins call it from the API.

Azure Advisor API Possible Limitations and Filter Issues

I manage many subscriptions so the current Azure Advisor while interesting requires you to go through too many screens and there is no way to download the CSV recommendations and compile them using PowerShell. This led to attempt to interface with the API. The issue I am having is that it appears that it limits you to 200 records so changing top does nothing. Many of the records are a generic security warning with a risk of none. I attempted to filter them out but my knowledge of API filters is poor and the documentation Microsoft provides could be better. Below is the PowerShell command I am using:
Call:
$Response = Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/${SubscriptionId}/providers/Microsoft.Advisor/Recommendations?api-version=2017-04-19&`$top=999&`$filter=risk -ne None" -Method GET -Headers #{"Authorization" = "$AccessToken"} -Verbose
Response:
Without Filter Parameter
https://management.azure.com/subscriptions/<SubID>/providers/microsoft.Advisor/recommendations?api-version=2017-04-19&$top=200&$s
kiptoken=<Token>
With Filter Parameter
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/${SubscriptionId}/providers/Microsoft.Advisor/Recommendations?api-version=2017-04-19&`$top=999&`$filter=risk -eq 'None'" -Method GET -Headers #{"Authorization" = "$AccessToken"} -Verbose
VERBOSE: GET https://management.azure.com/subscriptions/<sub ID>/providers/Microsoft.Advisor/Recommendations?api-version=2017-04-1
9&$top=999&$filter=risk -eq 'None' with 0-byte payload
Invoke-RestMethod : {"message":"Invalid $filter param"}
At line:1 char:13
+ $Response = Invoke-RestMethod -Uri "https://management.azure.com/subs ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have been struggling with exactly the same today, hence I found your article.
I managed to resolve my issue by using a later version of the API, and slightly changing the filter
For example:
$filter="Category eq 'Cost'"
$url = "https://management.azure.com/subscriptions/$Subscriptionid/providers/microsoft.Advisor/recommendations?api-version=2017-04-19&`$top=999&`$filter=$filter"
There is a mistake in your API. The right API grammar is &$filter not $filter, you could see your API, you lose a &.
The following script works for me.
##get token
$TENANTID=""
$APPID=""
$PASSWORD=""
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body #{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token
##set subscriptionId
$subscriptionId=""
$Headers=#{
'authorization'="Bearer $token"
'host'="management.azure.com"
'contentype'='application/json'
}
$url="https://management.azure.com/subscriptions/$subscriptionID/providers/Microsoft.Advisor/Recommendations?api-version=2017-03-31&`$top=999`&$filter=risk -eq 'None'"
Invoke-RestMethod -Uri $url -Headers $Headers -Method GET

Forward an email using rest api and powershell (Azure Automation)

I'm trying to forward emails with attachments to a specific email address via Azure Automation (with message ID). I get the error message at the bottom after I run the code. I'm not really sure am I on the right track here (both with email sending and sending of attachments). Perhaps there's a better way to do this.
Could anyone lend a hand?
$credObject = Get-AutomationPSCredential -Name "Myscreds"
$url = "https://outlook.office365.com/api/v1.0/me/AAMkADA1MTAAAH5JaL/forward"
$body = "{
""Message"":{
""Subject"": ""This is a test"",
""Importance"": ""Low"",
""Body"": {
""ContentType"": ""HTML"",
""Content"": ""This is great!""
},
""ToRecipients"": [
{
""EmailAddress"":{
""Address"": ""myname#test.com""
}
}
]
}}"
Invoke-RestMethod -Uri $url -Method Post -Credential $credobject -ContentType "application/json" -Body $Body
I get the following error message:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:24 char:1
+ Invoke-RestMethod -Uri $url -Method Post -Credential $credobject -Con ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Thanks.
Per the Microsoft documentation, you need to modify your request.
https://outlook.office.com/api/v1.0/me/messages/AAMkAGE0Mz8DmAAA=/forward
It looks like you forgot to include /messages/ in your request.
However, it looks like you want to change the body of a message when you forward it. This is more complicated, and you need to follow this workflow instead:
Alternatively, if you need to modify any updateable properties in the message to be forwarded, you can first create a draft forward message, update the message properties, and then send the reply.
Here's how that would look.
First, make a Draft of the message you want to forward
$request = "https://outlook.office365.com/api/v1.0/me/messages/AAMkADA1MTAAAH5JaL/createforward"
$body = {
"ToRecipients":[
{
""EmailAddress"":{
""Address"": ""myname#test.com""
}
}
],
"Comment": "Your sample message here"
}
The response back is going to include some properties, including the ID of the new message. You then use that to edit the Draft (to change the subject, etc) and then send it off. Let me know if you need any further help.
Ok. I had the incorrect message ID, that was my main problem. It's all resolved. I can forward messages with attachments using the message ID. Thanks again.
$credObject = Get-AutomationPSCredential -Name "mycreds"
$url = "https://outlook.office365.com/api/v1.0/Users('it-test#test.com')/messages/ASHJFKHFUISDFWIzLT=/forward"
$body = "{
""Comment"": ""A mail with some attachments (hopefully)"",
""ToRecipients"": [
{
""EmailAddress"":{
""Address"": ""myname#test.com""
}
}
]
}"
Invoke-RestMethod -Uri $url -Method Post -Credential $credobject -ContentType "application/json" -body $body

Using the attask api, how can update a task

Using the Attask api, how can a I add an update through the rest api? Updating the task looks like it will completely replace all updates as per the PUT documentation on nested objects, and doing a post on the /api/update doesn't seem to work : here is what I have tried so far using Powershell for testing
$url = "https:///attask/api/update?sessionID=$($session.data.sessionID)&message=Test Message from api&refObjID=56e9b1d100741c6eb3cab7df95269ba7&objCode=UPDATE&updateObjCode=NOTE"
$result = Invoke-RestMethod -Uri $url -Method "POST"
Result is :
Invoke-RestMethod : {"error":{"class":"java.lang.UnsupportedOperationException","message":null}}
Instead of Updates, post to notes instead - e.g.
$url = "https://lockton.attask-ondemand.com/attask/api/note?sessionID=$($session.data.sessionID)&updates={noteText:'Test Message from api',objID:'56e9b1d100741c6eb3cab7df95269ba7',noteObjCode:'TASK'}"
$postResult = Invoke-RestMethod -Uri $url -Method "POST"
$postResult

Powershell Invoke-RestMethod

I'm trying to create a powershell script to access DYN's API and perform checks/updates on DNS zones I use/test.
I'm following their API details and here's the first link, https://help.dyn.com/session-log-in/
Here's the beginning of the REST script I've put together:
$url = "https://api2.dynect.net/REST/Session/"
$body = #{customer_name='mahcompany';user_name='mahname';password='mahpass'}
Invoke-RestMethod -Method Post -Uri $url -Body $body
This produces the following results:
Invoke-RestMethod : The remote server returned an error: (406) Not Acceptable.
At line:12 char:9
+ $test = Invoke-RestMethod -Method Post -Uri $url -Body $body
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-> RestMethod], WebException
+ FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
This is supposed to be a JSON query according to the DYN information, and so I've tried sevveral other examples of DYN's using CURL as a basis:
$json = #"{"customer_name":"yourcustomer","user_name":"youruser","password":"yourpass"}'
However this doesn't work either.
Can anyone point me in the right direction here? This can't be that crazy, I'm just trying to pass the parameters into a rest-method query string. Any help would be very much appreciated at this point.
-Sean
Content Type
Invoke-RestMethod -Method Post -Uri $url -Body $body -ContentType 'application/json'
This might be the problem if dyn.com is expecting a proper content type.
According to the documentation on Invoke-RestMethod:
If this parameter is omitted and the request method is POST, Invoke-RestMethod sets the content type to "application/x-www-form-urlencoded". Otherwise, the content type is not specified in the call.
ConvertTo-JSON
You don't have to create your JSON string manually. You can create a hashtable and then convert it:
$data = #{
customer = 'something'
name = 'whatever'
}
$data | ConvertTo-JSON
I'm not saying that you are definitely making malformed JSON, but this can help prevent that.