Powershell Google Sheets API with service account, how do I set scopes? - powershell

I have a Google Sheet I want to fill using Google Cloud service account. So I've created the account, shared the sheet with it. I activate it with:
gcloud auth activate-service-account --key-file=XXX.json
and I put this in my powershell code:
$cred = gcloud auth print-access-token
$result = Invoke-RestMethod -Headers #{Authorization = "Bearer $cred"} -Uri
$requestUri -Method Post -ContentType "application/json" -Body $data
but I keep getting this error:
#{code=403; message=Request had insufficient authentication scopes.; status=PERMISSION_DENIED}
so my question is, where and how do I set scopes for service account?

Related

How to access Azure storage account Via Azure windows Virtual Machine Through Managed Identity

I am Trying to Access Azure Storage Account Via Azure Windows VM.
I followed This Microsoft Document Link: https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-datalake
I followed almost All steps That Mentioned In the above Document Link& JWT Access Token also Generated Successfully But My Commands For Uploading/Downloading Files are Throwing Errors.
Error: InvalidAuthenticationInfoAuthentication information is not given in the correct format
Please Correct me if i Used any wrong Commands For Download/Upload Files Via Virtual Machines Through Managed Identity
Commands Used For Generating JSW Token:
$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://adlsrg.blob.core.windows.net/' -Method GET -Headers #{Metadata="true"}
$content = $response.Content | ConvertFrom-Json
$AccessToken = $content.access_token
To access storage accounts, you need to generate access token for https://storage.azure.com resource.
I tried to reproduce the same in my environment and got below results:
I created one VM and enabled system-assigned managed identity like below:
Assign Storage Blob Data Contributor role to VM under your storage account as below:
Go to Azure Portal -> Storage accounts -> Your account -> Access Control (IAM) -> Add role assignment
Now connect to VM and run below PowerShell commands to get access token:
$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://storage.azure.com' -Method GET -Headers #{Metadata="true"}
$content = $response.Content | ConvertFrom-Json
$AccessToken = $content.access_token
Response:
To upload file to storage account, you can use below script:
$file = "C:\Users\sri\Desktop\hello.txt" #File path
$name = (Get-Item $file).Name
$url="https://sristorageacc5.blob.core.windows.net/sri/$($name)"
$RequestHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$RequestHeader.Add("Authorization", "Bearer $AccessToken")
$RequestHeader.Add("x-ms-version", "2019-02-02")
$RequestHeader.Add("x-ms-blob-type", "BlockBlob")
$result = Invoke-WebRequest -Uri $url -Method Put -Headers $RequestHeader -InFile $file
Response:
When I checked the same in Portal, file uploaded to container successfully like below:

Invoke Ansible API Token via Powershell

I have created a Token for Admin account. Now I am trying to invoke some API in ansible using the below
$headers=#{
Authorization="Bearer <token>"
}
$response=Invoke-WebRequest -Method GET -Uri "https://ansible.xyz.com/api/v2/job_templates" -Headers $headers -ContentType "application/json"
When I do run the above I get the following error:
Authentication credentials were not provided. To establish a login session, visit /api/login/.
I don't understand when I use Token to authenticate why it's still showing an error.
When I use the same auth token in postman or curl it's working fine.

need to add authentication header to azure devops api request

I'm trying to get information on my latest builds by sending a GET request to the Azure DevOps REST Api. I'm using Azure DevOps Server 2020 with the Patch 1 update. I need to add an authorization header to the request. The header I added is not working.
I'm doing the request in Powershell. Here's my code:
$PAT = 'personal access token'
$ENCODED = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($PAT))
$headers = #{
Authorization="Basic $ENCODED"
}
Invoke-RestMethod -Uri [azure devops server url]/[project name]/_apis/build/latest/Build?api-version=5.0 -Method Get -Headers $headers
When I run the code I get the error: Invoke Method: The format of value [PAT] is invalid
UPDATE:
I updated the header syntax. Now the reponse I get:
Invoke-RestMethod:
TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Server
I also tried passing my Azure DevOps username and password in the header like this:
$headers = #{
Authorization="Basic [domain\username]:[password]"
}
and I got this in response:
Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).
Do I have to enable some setting in Azure DevOps?
I usually reference to this demo to run REST API in PowerShell, it can work fine:
$uri = "request URI"
$pat = "personal access token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
. . .
$body = "{
. . .
}"
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST
In your case, the issue seems is caused by the encoding. Try using ASCII or UTF8, instead of Unicode.
To view more details, you can see "Use personal access tokens".

Create folder in user mailbox with Graph API

want to use the Graph API to create a folder in a user's mailbox that exists in Exchange Online.
As a result of the investigation, if I use "https://graph.microsoft.com/v1.0/users/testuser01#domain.com/mailFolders", I feel that it is possible, but an error is displayed and I cannot create it.
Currently, "Exchange> Mail.ReadWrite, MailboxSettings.ReadWrite" is assigned to the execution user (admin).
However, it says "Access is denied. Check credentials and try again." Is the permission wrong?
Or is the specified URL incorrect?
Sorry to trouble you, but thank you for your response.
【Append】
$body = #{
grant_type="client_credentials"
resource=$resource
client_id=$ClientID
client_secret=$ClientSecret
}
`#Get Token
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$TenantName/oauth2/token -Body $body
API Permissions
You are using the client credential flow to get the token to call Microsoft Graph - Create MailFolder, so you need to add the Application permission Mail.ReadWrite of Micrsoft Graph to your AD App.
1.Add the Application permission Mail.ReadWrite like below.
2.Click the Grant admin consent for xxx button, and make sure the $resource in your request is https://graph.microsoft.com.
Update:
Here is a powershell sample to call Create MailFolder API to create MailFolder.
$uri = "https://graph.microsoft.com/v1.0/users/joyw#xxxxx.onmicrosoft.com/mailFolders"
$headers = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer <access-token-here>'
}
$body = ConvertTo-Json #{
"displayName" = "testfolder1"
}
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body
Check the result in the Graph Explorer with List mailFolders:

How to authenticate without sending my username and password for HTTP requests?

Currently, following is how I am sending request from PS to update a parameter:
$pair="$("username"):$("password")"
$encodedCreds=[System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue="Basic $encodedCreds"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", $basicAuthValue)
$headers.Add("Content-Type", 'text/plain')
$headers.Add("Origin", 'https://teamcity.server.io')
Invoke-RestMethod -Method Put -Uri $url -Headers $headers -Body $updated_version
But I do not want my username and password mentioned like this anymore.
What other ways do I have to authenticate myself for HTTP requests made within from TeamCity Build Step through PS?
Had to use the basic auth but instead of using my own credentials used a super user created by the dev ops that is available to everyone in the company.