Check if current user has permissions to create work items - api

Is there an endpoint in TFS rest api that i can use to check if the current logged in user has enough permissions to create a new TFS work item ?

Try to use validation with the validateOnly parameter Work Items - Create.
PowerShell sample:
$pat = '<pat>'
$url = 'https://dev.azure.com/<org>/<project>/_apis/wit/workitems/$Task?validateOnly=true&api-version=6.1-preview.3'
$body = '[{"op":"add","path":"/fields/System.Title","from":null,"value":"Sample task"}]'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$pat)))
Invoke-RestMethod -Uri $url -Method Post -ContentType "application/json-patch+json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body
Result:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"TF237111: The current user does not have permissions to save work items under the specified area path.","typeName":"Microsoft.Azure.Boards.WebApi.Com
mon.PermissionDeniedException, Microsoft.Azure.Boards.WebApi.Common","typeKey":"PermissionDeniedException","errorCode":0,"eventId":3000}
At line:10 char:1
+ Invoke-RestMethod -Uri $url -Method Post -ContentType "application/js ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Related

PowerShell Invoke-WebRequest error with Go Daddy API

Following a script (from here) that many others have suggested works OK, I am having an error that is just outside my ability to understand. I am novice-to-intermediate with Power Shell and just beginning with API's.
The script is:
$domain = 'example.com' # your domain
$name = 'xyz' # name of the A record to update
$key = 'myKey # key for godaddy developer API
$secret = 'mySecret' # Secret for godday developer API
$headers = #{}
$headers["Authorization"] = 'sso-key ' + $key + ':' + $secret
$result = Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/records/A/$name -method get -headers $headers
$content = ConvertFrom-Json $result.content
$dnsIp = $content.data
# Get public ip address
$currentIp = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip
# THE CODE WORKS FINE UP TO HERE
if ( $currentIp -ne $dnsIp) {
$Request = #{ttl=3600;data=$currentIp }
$JSON = Convertto-Json $request
# THE FOLLOWING LINE FAILS WITH THE ERROR NOTED BELOW
Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/records/A/$name -method put -headers $headers -Body $json -ContentType "application/json"
}
The following error is returned for the final Invoke-WebRequest:
Invoke-WebRequest : {"code":"INVALID_BODY","fields":[{"code":"UNEXPECTED_TYPE","message":"is not a array","path":"records"}],"message":"Request body doesn't fulfill schema, see details in `fields`"}
At C:\tfsCode\tfs\api.ps1:25 char:5
+ Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/reco ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The Go Daddy reference page for the Get API is here and for the Put API is here.
The PUT API documentation says it’s expecting the body to be an array. This is also what the error message is saying. Try changing this line:
$Request = #{ttl=3600;data=$currentIp }
to
$Request = #(#{ttl=3600;data=$currentIp })
#() creates an array in PowerShell, when converted to JSON it will still be an array
#{} creates a hashtable in PowerShell, when converted to JSON it will be an object

Passing Credential on Invoke-RestMethod for AzureDevOps API to Retrieve Users

I am trying to create a powershell script that will retrieve a number of users from AzureDevOps organization using REST API. I have encrypted my password and placed it in credentials, however I am getting an error like this:
Invoke-RestMethod : Cannot process argument transformation on parameter
'Credential'.
userName
At D:\Others\Retrieve Users.ps1:11 char:80
+ ... stakeholderUrl -Method Get -Credential $webclient.Credentials).identi
...
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-RestMethod],
ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId :
ParameterArgumentTransformationError,Microsoft.PowerShell.
Commands.InvokeRestMethodCommand
Here is my Powershell Script Code:
$stakeholderUrl =
"https://vsaex.dev.azure.com/[organizationName]/_apis/userentitlements?api-
version=5.0-preview.2"
$password = Get-Content D:\GetUsers\password.txt | ConvertTo-SecureString -
Key (Get-Content D:\GetUsers\aes.key)
$credential = New-Object
System.Net.NetworkCredential("sample#abc.com",$password)
$stakeholder = (Invoke-RestMethod -Uri $stakeholderUrl -Method Get -
Credential $credential).identities
$StakeholderUsers = #()
foreach($user in $stakeholder){
$customObject = new-object PSObject -property #{
"Display Name" = $user.displayName
"Email" = $user.mailAddress
"License" = $user.licenseDisplayName
}
$StakeholderUsers += $customObject
}
$StakeholderUsers | Select `
displayName,
mailAddress,
licenseDisplayName
I would appreciate if you could help me on this.
Thanks!
Store the credentials in this way:
domain\username:password
$Credentials= Get-Content D:\GetUsers\Credentials.txt
Create the Base64-encoded Basic authorization header:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}" -f $Credentials)))
Invoke the rest:
$result = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}

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

API: Trying to set name of an appveyor project

I am trying to create an appveyor project using powershell and set my own name.
function Invoke-AppveyorCreateProject {
param (
[System.String] $appveyorProjectName,
[System.String] $repositoryName
)
# step 1, create project
$project = #{
repositoryProvider="gitHub"
repositoryName="esskar/$repositoryName"
isPrivate=$true
}
$json = $project | ConvertTo-Json
$project = Invoke-RestMethod -Method Post -Uri "$AppveyorApiUrl/projects" -Headers $AppveyorRestHeaders -Body $json -ContentType "application/json"
# step 2, update project
$project.name = $appveyorProjectName
$json = $project | ConvertTo-Json
$project = Invoke-RestMethod -Method Put -Uri "$AppveyorApiUrl/projects" -Headers $AppveyorRestHeaders -Body $json -ContentType "application/json"
}
# Globals
$AppveyorApiUrl = 'https://ci.appveyor.com/api'
$AppveyorApiToken = $env:AppveyorApiToken
$AppveyorRestHeaders = #{
"Authorization" = "Bearer $AppveyorApiToken"
"Content-type" = "application/json"
}
$AppveyorAccountName = $env:AppveyorAccountName
Invoke-AppveyorCreateProject "foo.bar" "repo1"
Step 1 works, the project is created, but when I try to change the name, i get an exception
Invoke-RestMethod : {"message":"Object reference not set to an instance of an object."}
At appveyortest.ps1:20 char:16
+ ... $project = Invoke-RestMethod -Method Put -Uri "$AppveyorApiUrl/proje ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
when i try to set the name during creation in step 1, then name is not used, and project has the same name as without setting the name.
Use the following code for the Step 2:
$settings = Invoke-RestMethod -Uri "$AppveyorApiUrl/projects/$($project.accountName)/$($project.slug)/settings" -Headers $AppveyorRestHeaders -Method Get
$settings.settings.name = $appveyorProjectName
Invoke-RestMethod -Uri "$AppveyorApiUrl/projects" -Headers $AppveyorRestHeaders -Body ($settings.settings | ConvertTo-Json -Depth 10) -Method Put

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.