I need reource code of main.iam.ad.ext.azure.us - azure-gov

I need to collect information about total and assigned licenses programmatically.
The way that is described here: https://tech.nicolonsky.ch/manage-azure-ad-group-based-licensing-with-powershell/ - does not work on AzureUSGovernment environment. The following error occurs: ""Get-AADLicenseSku : AADSTS900382: Confidential Client is not supported in Cross Cloud request."
So, I am looking for a way to adjust it and use it on AzureUSGovernment. But I could not find the resource ID of main.iam.ad.ext.azure.us
As I understood, the ID of main.iam.ad.ext.azure.com is 74658136-14ec-4630-ad9b-26e160ff0f. But I do not understand where it is coming from.
Thank you in advance for the help.
I created a script based on the original scripts:
$context = Get-AzContext
if ($null -eq $context) {
$null = Connect-AZAccount -EA stop
$context = Get-AzContext
}
$apiToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id, $null, "Never", $null, "https://main.iam.ad.ext.azure.us")
$header = #{
'Authorization' = 'Bearer ' + $apiToken.AccessToken.ToString()
'Content-Type' = 'application/json'
'X-Requested-With' = 'XMLHttpRequest'
'x-ms-client-request-id' = [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()
}
Write-Verbose "Connected to tenant: '$($context.Tenant.Id)' as: '$($context.Account)'"
$baseUrl = "https://main.iam.ad.ext.azure.us/api/"
try {
$request = Invoke-WebRequest -Method Get -Uri $($baseUrl + "AccountSkus") -Headers $header
$requestContent = $request | ConvertFrom-Json
return $requestContent
}
catch {
# convert the error message if it appears to be JSON
if ($_.ErrorDetails.Message -like "{`"Classname*") {
$local:errmsg = $_.ErrorDetails.Message | ConvertFrom-Json
if ($local:errmsg.Clientdata.operationresults.details) {
Write-Error $local:errmsg.Clientdata.operationresults.details
}
else {
Write-Error $local:errmsg
}
}
else {
Write-Error $_
}
}
But it fails with the following error:
"Invoke-RestMethod :
401 - Unauthorized: Access is denied due to invalid credentials.
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied."
I tried to use the user account and service principal. Global Admin role is assigned to both.

I found the solution. In my script above ^^, I replaced
$apiToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id, $null, "Never", $null, "https://main.iam.ad.ext.azure.us")
with
$apiToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id, $null, "Never", $null, "ee62de39-b9b0-4886-aa58-08b89c4e3db3")
And now it works. Here is the example of the response:
name : Office 365 E3 - GCCHIGH
accountId : XXXXXX-XXXX-4427-8719-XXXXXXXXXXXX
accountSkuId : TEST:ENTERPRISEPACK_USGOV_GCCHIGH
availableUnits : 0
totalUnits : 1
consumedUnits : 1
skuId : aea38a85-XXXX-XXXX-aa00-XXXXXXXXXXXX
isDepartment : False
warningUnits : 0
serviceStatuses : {#{provisioningStatus=Success; servicePlan=}, #{provisioningStatus=Success; servicePlan=}, #{provisioningStatus=Success; servicePlan=}, #{provisioningStatus=Success; servicePlan=}...}

Related

Azure DevOps Services REST API 6.0: Deployments/Release - List not returning count more than 100

Azure DevOps Services REST API 6.0: Deployments/Release - List not returning count more than 100
I'm using doc (Build, Release & Deployment List)
https://learn.microsoft.com/en-us/rest/api/azure/devops/release/deployments/list?view=azure-devops-rest-6.0&tabs=HTTP
Below API call is giving me list of total builds (approx 930)
GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?$top=999&api-version=6.0
Whereas it wont show more than 100 releases/deployments with below queries
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?$top=999&api-version=6.0
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/deployments?$top=999&api-version=6.0
please suggest further if you have any solutions.
Please try this PowerShell script:
[string]$orgurl = "https://vsrm.dev.azure.com/{organization}"
[string]$project = "ProjectName"
[string]$user = ""
[string]$token = "PAT"
[System.Net.ServicePointManager]::SecurityProtocol = "tls12"
# Ignore the error
$ErrorActionPreference = 'SilentlyContinue'
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
cls
$headers = #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
$continuationToken = ''
$deployments = #()
Do {
$uri = "$orgurl/$project/_apis/release/deployments?api-version=6.0&continuationToken=$ContinuationToken"
$result = Invoke-WebRequest -Uri $uri -Headers $headers
$deployments += ($result.Content | ConvertFrom-Json).Value
$continuationToken = $result.Headers.'x-ms-continuationtoken'
Write-Host "continuationToken:" $continuationToken
}
While($continuationToken)
$deployments.Count
$deployments.release | Select id, name, url
I got it to work by the first time not passing the ContinuationToken parameter the first call.
$uri = "$orgurl/$project/_apis/release/deployments?api-version=6.0"
Do {
$result = Invoke-WebRequest -Uri $uri -Headers $headers
$uri = "$orgurl/$project/_apis/release/deployments?api-version=6.0&continuationToken=$ContinuationToken"
$deployments += ($result.Content | ConvertFrom-Json).Value
$continuationToken = $result.Headers.'x-ms-continuationtoken'
}

Why does the array stop storing when an error happens?

I have been working on the following code that supposedly retrieves all powerbi reports from the server, checks if they have refresh plans, if they dont, it outputs "No refresh pans exist..", and if it does have it, then it outputs refreshplan info like description.
$webPortalURL = "https://server-pbi.domain.com/reports"
$PBI_Reports_Array = #()
$PBI_Reports_Array = $(Invoke-RestMethod -UseDefaultCredentials -uri $($webPortalURL + "/api/v2.0/PowerBIReports"))
$loopCount = 0
$refreshPlanArray = #()
foreach ($reportPath in $PBI_Reports_Array.value.path) {
$refreshPlanArray += $(Invoke-RestMethod -UseDefaultCredentials -uri $($webPortalURL + "/api/v2.0/PowerBIReports(path='" + $reportPath + "')/CacheRefreshPlans"));
write-host "$($refreshPlanArray[$loopCount])" -foregroundcolor magenta; #testing output here to debug
if ([string]::IsNullOrEmpty($($refreshPlanArray[$loopCount].value))) {
write-host "$loopCount | $reportPath | No Refresh Plan Exists for this report!";
}
else {
write-host "$loopCount | $reportPath | $($refreshPlanArray[$loopCount].value.Description) | $($refreshPlanArray[$loopCount].value.ScheduleDescription)" -foregroundcolor magenta;
}
$loopCount++;
}
i am running into a weird bug. so i have 2 servers/portals, on one of the servers/portals, when i run this script, it retrieves all reports and does exactly what i am expecting it do as described above.
when i thought i finished developing the script, i tested it on production portal/server and it wasnt working as expected!
i debugged for many hours until i think i found whats happening, but idk what to do about it:
basically, the reason why it worked on one server/portal but not the other is because the nonproduction portal/server didnt have this error:
Invoke-RestMethod : The remote server returned an error: (404) Not Found.
apparently, before that error happened on the production server/portal where this failed, this line write-host "$($refreshPlanArray[$loopCount])" i added for debugging purposes was printing the following odata contexts up until the error happened!
#{#odata.context=https://server-pbi.domain.com/reports/api/v2.0/$metadata#CacheRefreshPlans; value=System.Object[]}
then when the error occurred after iteration 4, it stopped printing the odata!
why is that?
I figured it out!
$loopCount is the culprit! it has to be inside a try, or the "good" part of the code, otherwise, the array indexing gets messed up with the 404 NULL value
This is the correct code:
$webPortalURL = "https://server-pbi.domain.com/reports"
$PBI_Reports_Array = #()
$PBI_Reports_Array = $(Invoke-RestMethod -UseDefaultCredentials -uri $($webPortalURL + "/api/v2.0/PowerBIReports"))
$loopCount = 0
$refreshPlanArray = #()
foreach ($reportPath in $PBI_Reports_Array.value.path) {
try {
$refreshPlanArray += $(Invoke-RestMethod -UseDefaultCredentials -uri $($webPortalURL + "/api/v2.0/PowerBIReports(path='" + $reportPath + "')/CacheRefreshPlans"));
if ([string]::IsNullOrEmpty($($refreshPlanArray[$loopCount].value))) {
write-host "$loopCount | $reportPath | No Refresh Plan Exists for this report!";
}
else {
write-host "$loopCount | $reportPath | $($refreshPlanArray[$loopCount].value.Description) | $($refreshPlanArray[$loopCount].value.ScheduleDescription)" -foregroundcolor magenta;
}
$loopCount++;
}
catch {
}
}

Coinbase API invalid signature with Powershell

I would like to retrieve account balance through Coinbase API with Powershell.
I coded the following reading from coinbase api documentation but the last request throws the following error:
Invoke-RestMethod : {"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Here is my code.
What's wrong? Thank you.
$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch
$method = 'GET'
$requestpath = '/v2/accounts'
$secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($secret_key)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($sign))
$signature = [Convert]::ToBase64String($signature)
$header = #{
"CB-ACCESS-SIGN"=$signature
"CB-ACCESS-TIMESTAMP"=$epochtime
"CB-VERSION" = '2017-08-07'
"CB-ACCESS-KEY"='xxxxxxxxxxxxxx'
}
Invoke-WebRequest $accounts -Headers $header
Hopefully this will get you going. I just started working on a module today and got stuck on the same thing. I came across your question while trying to solve the problem myself. Figured I would share what I found. Good luck!
$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch
$method = 'GET'
$requestpath = '/v2/accounts'
$secret_key = (Get-CoinBaseAPIKeys).Secret
$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret_key)
$computeSha = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($sign))
The LONG WAY, for reference:
$signature = ""
foreach ( $c in $computeSha )
{
$signature += "{0:x2}" -f $c
}
The short way. Oddly I got stuck on this SAME issue, because the short way
produces UPPER CASE HEX and the long way ^^above^^ converts to lower case HEX.
The CoinBase API will ONLY accept the signature in HEX in lower case.
$signature = ([System.BitConverter]::ToString($computeSha) -replace "-").ToLower()
Now that we have the signature figured out, the rest should work great. I removed the CB_VERSION because it will default to your OWN API version. My default was different, so I simply removed it.
$header = #{
"CB-ACCESS-SIGN"=$signature
"CB-ACCESS-TIMESTAMP"=$epochtime
"CB-ACCESS-KEY"=(Get-CoinBaseAPIKeys).Key
}
$result = Invoke-WebRequest $accounts -Headers $header -Method Get -ContentType "application/json"
$accounts = $result.Content | ConvertFrom-Json
Write-Output $accounts.data
As an aside on storing PRIVATE KEY/SECRET you can find some ideas here:
https://github.com/cmaahs/BittrexAPI/tree/master/Encryption. Feel free to grab it and modify as you will. Better to store your KEY/SECRET encrypted in the registry rather than as plain text in your script or as environment variables.

How to query REST API

I am using this code below to deal with the REST API query for Adobe Analytics. I always get the message "something went wrong" which means that the first IF is not active.
include_once('/path/SimpleRestClient.php');
$username = 'XXXXX';
$secret = 'XXXXX';
$nonce = md5(uniqid(php_uname('n'), true));
$nonce_ts = date('c');
$digest = base64_encode(sha1($nonce.$nonce_ts.$secret));
$server = "https://api.omniture.com";
$path = "/admin/1.4/rest/";
$rc=new SimpleRestClient();
$rc->setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
$query="?method=Company.GetTokenUsage";
$rc->getWebRequest($server.$path.$query);
if ($rc->getStatusCode()==200)
{
$response=$rc->getWebResponse();
var_dump($response);
}
else
{
echo "something went wrong\n";
var_dump($rc->getInfo());
}
The $rc->getStatusCode(); does not exit. I get '404' when I use this line :
print_r ($rc->getStatusCode());
After googling, I found https://marketing.adobe.com/developer/blog/how-to-start-with-the-omniture-rest-api-in-php. It uses API version of 1.3 instead of 1.4. By updating the
$path = "/admin/1.4/rest/";
to
$path = "/admin/1.3/rest/";
I was able to stop getting 404 errors in the browser.

Why do I get HTTP 401 Unauthorized from my call the to Yahoo contacts API?

This is driving me crackers. I'm implementing a friend invite scheme on a website and need access to the user's Yahoo contacts list. To do this, I'm using OAuth and the yahoo REST api. Here's a complete rundown of the sequence of events:
I have a project set up on developers.yahoo.com which is configured to have read access to Contacts. It's on a made-up domain which I point to 127.0.0.1 in my hosts file (On the off-chance that localhost was causing my woes). For this reason, the domain is not verified though my understanding is that this simply means I have less restrictions, not more.
Firstly, on the server I get a request token:
https://api.login.yahoo.com/oauth/v2/get_request_token
?oauth_callback=http%3A%2F%2Fdev.mysite.com%2Fcallback.aspx
&oauth_consumer_key=MYCONSUMERKEY--
&oauth_nonce=xmaf8ol87uxwkxij
&oauth_signature=WyWWIsjN1ANeiRpZxa73XBqZ2tQ%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1328796736
&oauth_version=1.0
Which returns with (Formatted for vague attempt at clarity):
oauth_token=hxcsqgj
&oauth_token_secret=18d01302348049830942830942630be6bee5
&oauth_expires_in=3600
&xoauth_request_auth_url
=https%3A%2F%2Fapi.login.yahoo.com%2Foauth%2Fv2%2Frequest_auth
%3Foauth_token%3Dhxcsqgj
&oauth_callback_confirmed=true"
I then pop-up the xoauth_request_auth_url page to the user and receive a verifier code to my callback page. I then send that back to my server so that I can exchange it for an access token:
https://api.login.yahoo.com/oauth/v2/get_token
?oauth_consumer_key=MYCONSUMERKEY--
&oauth_nonce=yxhd1nymwd03x189
&oauth_signature=c%2F6GTcybGJSQi4TOpvueLUO%2Fgrs%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1328796878
&oauth_token=hxcqgjs
&oauth_verifier=b8ngvp <- verifier given via callback
&oauth_version=1.0
That seems to work, and I get an access token back:
oauth_token=MYVERYLONGACCESSTOKEN--
&oauth_token_secret=MYOATHTOKENSECRET
&oauth_expires_in=3600
&oauth_session_handle=ADuXM093mTB4bgJPKby2lWeKvzrabvCrmjuAfrmA6mh5lEZUIin6
&oauth_authorization_expires_in=818686769
&xoauth_yahoo_guid=MYYAHOOGUID
I then immediately attempt to get the contacts list with the access token and the GUID:
http://social.yahooapis.com/v1/user/MYYAHOOGUID/contacts
(HTTP Header added and formatted with line breaks for clarity...)
Authorization: OAuth
realm="yahooapis.com",
oauth_consumer_key="MYCONSUMERKEY--",
oauth_nonce="nzffzj5v82mgf4mx",
oauth_signature="moVJywesuGaPN5YHYKqra4T2ips%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1328796907",
oauth_token="MYVERYLONGACCESSTOKEN--",
oauth_version="1.0"
From this call I get a 401 Unauthorized, but it seems impossible to find out why. To sign these calls, I'm using this oath lib on github. I don't think it's doing anything extraordinary or incompatable. For the signature, I'm including the consumer key/secret and the access token/secret. I've looked at the signature base that's being hashed and it looks to be the same form as the examples visible on yahoo's documentation. I'm guessing that I'm missing something from the parameters that isn't being hashed. Is there a way to find out why the call is unauthorized, or does anyone know of an example showing exactly what form the signature base and authorization header must take?
Solved this myself. Adding the answer just in case it happens to help anyone who makes the same silly mistake I did. When I made the API call, I was using the token secret returned from the original request token call instead of the new one returned from the access token call.
Oops.
this is the code with which I solved, the trusted code to use if yahooapis returns 403 forbidden:
Reference:
https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
https://github.com/danzisi/YQLQueryYahooapis
init CODE
/**
* Call the Yahoo Contact API
*
* https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
*
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $guid obtained from getacctok
* #param string $access_token obtained from getacctok
* #param string $access_token_secret obtained from getacctok
* #param bool $usePost use HTTP POST instead of GET
* #param bool $passOAuthInHeader pass the OAuth credentials in HTTP header
* #return response string with token or empty array on error
*/
function call_yql($consumer_key, $consumer_secret, $querynum, $access_token, $access_token_secret, $oauth_session_handle, $usePost=false, $passOAuthInHeader = true){
global $godebug;
$response = array();
if ($consumer_key=='' || $consumer_secret=='' || $querynum=='' || $access_token=='' || $access_token_secret=='' || $oauth_session_handle) return array('0' => 'Forbidden');
if ($querynum == 1) {
$url = 'https://query.yahooapis.com/v1/yql';
// Show my profile
$params['q'] = 'select * from social.profile where guid=me';
} elseif ($querynum == 2) {
$url = 'https://query.yahooapis.com/v1/yql';
// here other query
}
$params['format'] = 'json'; //json xml
$params['Authorization'] = 'OAuth';
$params['oauth_session_handle'] = $oauth_session_handle;
$params['realm'] = 'yahooapis.com';
$params['callback'] = 'cbfunc';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_callback'] = 'oob';
$params['oauth_token'] = $access_token;
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] = oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params, $consumer_secret, $access_token_secret);
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, true);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("call_yql:INFO:request_url:$request_url");
logit("call_yql:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ? ('?' . $query_parameter_string) : '' );
logit("call_yql:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($godebug==true) {
echo "<p>Debug: function call_yql info: <pre>" . print_r($info, TRUE) . "</pre></p>";
echo "<p>Debug: function call_yql header: <pre>" . print_r($header, TRUE) . "</pre></p>";
echo "<p>Debug: function call_yql body: <pre>" . print_r($body, TRUE) . "</pre></p>";
}
if ($body) {
$body = GetBetween($body, 'cbfunc(', ')');
$full_array_body = json_decode($body);
logit("call_yql:INFO:response:");
if ($godebug==true) echo "<p>Debug: function call_yql full_array_body: <pre>" . print_r($full_array_body, TRUE) . "</pre></p>";
}
}
// return object
return $full_array_body->query;
}
END code