$LoginUrl = "https://login.microsoft.com"
$Tenantname = "xxxx"
$Body = # {
client_id = "xxxx"
client_secret = "xxxx"
resource = "https://graph.microsoft.com"
grant_type = "client_credentials"
}
$oauth = Invoke-RestMethod -Method Post -Uri $LoginUrl/$Tenantname/oauth2/v2.0/token -Body $Body
Above is my Authentication to get token for Graph API, application registration has been done. Below error when I use the v2.0 for token.
Invoke-RestMethod: {"error":"invalid_request","error_description":"AADSTS901002: The 'resource' request parameter is not supported" ......}
But, I can get it run when I used below, that I searched from website.
I got confused where is wrong, and why below v1.0 is working.
$oauth = Invoke-RestMethod -Method Post -Uri $LoginUrl/$Tenantname/oauth2/token?api-version=1.0 -Body $Body
As documented here, you don't need the resource-parameter (you can read that from the error message) for v2-auth. But what you are missing and is required according to the docu:
scope
Required
The value passed for the scope parameter in this request should be the resource identifier (Application ID URI) of the resource you want, affixed with the .default suffix. For Microsoft Graph, the value is https://graph.microsoft.com/.default. This value informs the Microsoft identity platform endpoint that of all the application permissions you have configured for your app, it should issue a token for the ones associated with the resource you want to use.
Related
I am trying to POST a payload to the web server using Simple.OData.Client in .Net application.
I have the following parameters:
Authorization = 'OAuth 2.0'
Grand Type = 'Authorization Code'
Callback URL = 'https://myserver.com/*'
Auth URL = 'https://myserver.com/auth'
Access Token URL = 'https://myserver/token'
Client ID = 'id'
Client Secret = 'secret'
Scope = 'openid'
Token Name = 'name'
I also have URL and endpoint for POST.
Using these parameters I can get Access Token and POST data successfully using Postman, the problem is to implement that on C#.
As I understand it has to be 2 steps process: get Access Token, post.
Could someone provide code for getting Access Token?
I'm trying to edit a file's last version on TFS using the example shown over here:
https://learn.microsoft.com/en-us/rest/api/azure/devops/tfvc/changesets/create?view=azure-devops-rest-5.0
But this request demands the file's version to be edited.
Is there a way to edit a file's last version without passing the actual file version?
Thanks in advance,
Is there a way to edit a file's last version without passing the actual file version?
Based on my test, the version field is required.
So When you use the Rest API to edit a file from TFVC repo, you need to input the latest version.
But you could use the Rest API:Changesets - Create to get the latest version number
Here is a PowerShell Script example:
$token = "PAT"
$url="https://dev.azure.com/{Organization Name}/{Project Name}/_apis/tfvc/changesets?$orderby=id des&api-version=5.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
$latestversion = $response.value.changesetId[0]
echo $latestversion
$url2="https://dev.azure.com/{Organization name}/_apis/tfvc/changesets?api-version=5.0"
$body = "{
`"changes`": [
{
`"item`": {
`"version`": `"$latestversion`",
`"path`": `"$/TFVCTEST/test.txt`",
`"contentMetadata`": {
`"encoding`": 1200,
`"contentType`": `"text/plain`"
}
},
`"changeType`": `"edit`",
`"newContent`": {
`"content`": `"Initial coassdntentssss sas of 4/9/2019 11:21:13 PM\nEdited contents`"
}
}
],
`"comment`": `"(sample) Editing the file via API`"
}"
$response2 = Invoke-RestMethod -Uri $url2 -Headers #{Authorization = "Basic $token"} -Method Post -Body $body -ContentType application/json
Explanation:
The first URL is used to get all changestIDs, the results are sorted in descending order by default. So you only need to take the first value that is the latest value.
Then you could set the latest value as version in the request body of second Rest API to edit the files.
By the way, considering that you are using TFS, you may need to change the url to the following:
Changesets - Get Changesets
Changesets - Create
I'm guessing this is a permission issue. I know the URI and body, etc are all correct, as it works fine with a different authorisation in the header.
I tried adjusting permissions under _admin/_versioncontrol to 'Allow', as per what had worked for me when creating pull requests. Ref:
Getting a '403 Forbidden' when calling the Pull Request API on VSTS
But while I can create/abandon requests just fine, I can't seem to auto-complete them.
What am I missing?
Edit 1 (based on starian chen-MSFT's request):
When I catch the exception in my powershell script and do a Write-Output $_.Exception, I get this:
The remote server returned an error: (400) Bad Request.
When I remove the Invoke-RestMethod from a try-catch block, I get this printed to the consolve output:
2018-03-10T03:22:13.3706092Z Calling https://<my_vsts_account>.visualstudio.com/DefaultCollection/_apis/git/repositories/<my_git_repo_id>/pullRequests/<my_pr_id>?api-version=3.0 with body:
2018-03-10T03:22:13.3727606Z {
2018-03-10T03:22:13.3727838Z "autoCompleteSetBy": {
2018-03-10T03:22:13.3728135Z "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
2018-03-10T03:22:13.3728388Z },
2018-03-10T03:22:13.3728593Z "completionOptions": {
2018-03-10T03:22:13.3728942Z "mergeCommitMessage": "Auto completing pull request",
2018-03-10T03:22:13.3729252Z "squashMerge": "false",
2018-03-10T03:22:13.3729845Z "deleteSourceBranch": "false"
2018-03-10T03:22:13.3730053Z }
2018-03-10T03:22:13.3730229Z }
2018-03-10T03:22:13.6040452Z ##[error]Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Invalid argument value.\r\nParameter name: Invalid
pull request auto complete set by id. Valid values are either the current user identity id, or an empty guid (to unset
auto complete).","typeName":"Microsoft.TeamFoundation.SourceControl.WebServer.InvalidArgumentValueException,
Microsoft.TeamFoundation.SourceControl.WebServer","typeKey":"InvalidArgumentValueException","errorCode":0,"eventId":0}
At C:\Development\.agent\scripts\do-ci.ps1:562 char:33
+ ... ry_result = Invoke-RestMethod -Uri $uri -Method Patch -UseDefaultCred ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Once again, when I copy paste the above URI and body into Postman, it works perfectly fine. Seeing that the only difference between my Powershell script and the Postman call is the authorization header, it means this is a permission issue, and a permission issue alone.
You need to specify the same user id (current authorized user) to update pull request to Auto-Complete through REST API ("autoCompleteSetBy":{"id":xxx}), otherwise you will get 400 error.
You can update pull request status to Completed through REST API if you just want to complete the pull request.
Update:
Simple code to create pull request and get user's id:
param(
[string]$project,
[string]$repo,
[string]$sourceBranch,
[string]$targetBranch,
[string]$title,
[string]$des,
[string]$token
)
$bodyObj=#{
"sourceRefName"="refs/heads/$sourceBranch";
"targetRefName"= "refs/heads/$targetBranch";
"title"= "$title";
"description"="$des";
}
$bodyJson=$bodyObj| ConvertTo-Json
$uri="https://XXX.visualstudio.com/DefaultCollection/$project/_apis/git/repositories/$repo/pullRequests?api-version=3.0"
Write-Output $bodyJson
Write-Output $uri
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "test",$token)))
$result=Invoke-RestMethod -Method POST -Uri $Uri -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $bodyJson
$serviceId=$result.createdBy.id
Write-Host $serviceId
Write-Host "##vso[task.setvariable variable=userId;]$serviceId"
I am using OAuth 2.0 for authorization according to this documentation :(https://developers.vendhq.com/documentation/oauth.html#oauth) and having this error:
"error": "invalid_request", "error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"grant_type\" parameter."
Request
Method : POST
Content-Type: application/x-www-form-urlencoded
URL : https://{domain_prefix}.vendhq.com/api/1.0/token
Parameters :
code = {code}
client_id = {app_id}
client_secret = {app_secret}
grant_type = authorization_code
redirect_uri = {redirect_uri}
As per the RFC6749, section 4.1.3, the encoded body of a POST request should look like code={code}&client_id={app_id}&client_secret={app_secret}&grant_type=authorization_code&redirect_uri={redirect_uri}.
Example:
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb&client_id=CLIENT_ID_1234&client_secret=CLIENT_SECRET
Do not forget to encode the redirect Uri: http://foo.bar/ => http%3A%2F%2Ffoo.bar%2F
Concerning the authentication error, it may be because the authorization server do not support client secret in post request (or your client is not allowed to use it).
Then try to add the Authorization header with basic authentication scheme.
The value of this header is Basic {ENCODED_AUTHENTICATION} with {ENCODED_AUTHENTICATION} =base64(client_id + ':' + client_secret)
With this header, the client_id and client_secret in the post request have to be removed. Your request parameters become code={code}&grant_type=authorization_code&redirect_uri={redirect_uri}.
You will need to check the URL to which you are attempting to send your POST to. The service that you are attempting to contact does not exist or is currently unavailable.
i have following params:
$url = "https://example.com/auth_token.json"
$clientId = "...", $secretId = "..."
$callback = "http://example"
$code = "1234" - # i've received if earlier,
$body = "grant_type=authorization_code&code=$code&redirect_uri=$callback"
My goal is to get token with code, service says :
"Send a POST request to $url, providing the Client ID and Secret Key as HTTP Basic Authorization credentials, and a post body containing grant_type=authorization_code
and get in response json with token."
I tried something like this
curl $url --verbose -d $body -X -POST
but answer is - Status :401, nonauthorized and json "Unauthorized client or authentication failed, check your credentials."
then i tried to add
-H "Authorization : Basic ...encoded value..."
and get "Bad request"
Help me please, i missed something,
thx