Partner Central rest api 401 unauthorized access - rest

I followed the Microsoft doc to get the billing profile of a customer.
With the auth tutorial with the Powershell Code
$credential = Get-Credential
Connect-PartnerCenter -Credential $credential -ServicePrincipal -TenantId '<TenantId>'
Copied the access token and produced a Postman Get request but still got an 401 unauthorized request
It could be from the security update of Microsoft , but the Auth documentation is from january so i think These are the steps to get access to the parner central
https://www.microsoftpartnercommunity.com/t5/UK-Partner-Zone-Discussions/FY19-CSP-program-new-mandatory-security-requirements/td-p/6981
Or I don't have the right permissions as a user to get the billing profile.
I know it's one step that I oversee or that it's one thing that I did wrong but I can't see it
I am aware that there are some questions on stackoverflow about this issue. But Can't seem to find a solution there

Tried to get the access token with this Powershell code:
$appId = 'xxxxxxxxxxxxxxxxxxxxx'
$appSecret = 'xxxxxxxxxxxxxxxx' | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $appId, $appSecret
$token = New-PartnerAccessToken -Consent -Credential $credential -Resource https://api.partnercenter.microsoft.com -ServicePrincipal
New-PartnerAccessToken -RefreshToken $token.RefreshToken -Resource https://api.partnercenter.microsoft.com -Credential $credential -ServicePrincipal
Source and probably more explanation to this you can find here: docs
If the link becomes invalid search for Partner Consent process for the Partner Center
Hope this one helps you out, this was what worked for me. Struggled a lot to find this out also.
Also make sure in your Azure AD app you select access token in the Authentication Setting beneath Implicit grant. And to select , urn:ietf:wg:oauth:2.0:oob beneath the suggested redirect URL's

which token you tried to access the Partner center api. First you have to generate the token by registering app with Partner center.
You have to use client/application id, tenant id/domain name, client secret.
Use that token to access the partner center api.

Related

Execute an App registration without AzureAD

For a professional project, a chunk of the pipeline must be able to create an application (the first App registration, so I only have a global Admin) automatically within Azure AD. So far I used AzureAD which works well with Powershell 5.6 on Windows.
I now must be able to run the code with Ubuntu 20.04 and its Powershell 7.2. Unfortunately for me, AzureAD module is only supported on non-core Windows PowerShell, therefore it does not work on core PS6 or PS7. A very simplified piece of code is the following:
# Connection infos
$tenantId = "abcdef12345-1234-1234-124-abcdef12346789"
$account = "my_admin#domain.com" # Is cloud Admin by default
$password = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($account, $password)
Connect-AzureAD -Credential $psCred -Tenant $tenantId
# Create app
$appName = "MyApp"
New-App -appName $appName -tenant_id $tenantId
I am stuck and my question is the following: how could I run such an operation with Powershell 7.2 considering AzureAD is not usable? I did check Connect-MgGraph for the connection part only (https://github.com/microsoftgraph/msgraph-sdk-powershell) but the clientId is an infos that I don't have -and want to create-.
Thanks in advance
You can use DeviceLogin as explained in this article to obtain an oAuth access token for you Global Administrator account in PowerShell (independent of the version) but this first step needs a human interaction.
After obtaining the token, you can use it to make Graph API calls with your Global Administrator permissions to create an application.
Once you create your first application, you must attribute required permissions and use it to automate the process (obtain token programmatically using API calls) for application creation in PowerShell.
You could use Resource Owner Password Credentials (ROPC) to authenticate, however Microsoft actively discourages it in their documentation due to the security implications of sending a password over the wire.
If the security issues present with this method of authentication are still tolerated within your acceptance criteria, you would still need a ClientID. Luckily, AzureAD has a well-known ClientID that you can use to authenticate. This ID is 1950a258-227b-4e31-a9cf-717495945fc2
The below Powershell code should get you started. I've basically translated the HTTP request within Microsoft's documentation into a splatted Invoke-RestMethod command.
$LoginWithROPCParameters = #{
URI = "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token"
Method = "POST"
Body = #{
client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
scope = "user.read openid profile offline_access"
username = "username#contoso.onmicrosoft.com"
password = "hunter2"
grant_type = "password"
}
}
Invoke-RestMethod #LoginWithROPCParameters

Powershell: Get-MsalToken error AADSTS7000218

Running the following Powershell command
$tokenresponse = Get-MsalToken -ClientId $clientID -TenantId $tenantID -Interactive -RedirectUri "http://localhost"
gives me the error:
AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.
All solutions I found are pointing to the direction, that in the Azure Protal I should enable "Allow public client flows" but this setting is enabled. Any idea how I can get the token (I would need to get a token for delegated permissions)
I know this is an old question, but my answer below might help someone in the future. I ran into this same problem today and the way to fix it was by correcting the configuration on the App Registration. The solution was quite simple. I just had to set up Authentication to the right platform: "Mobile and desktop applications". Instead of Web or SPA.
To test it, get your tenant id and application (client) id, and pass it to the Get-MsalToken commandlet like below. The login page should pop-up, including any MFA dialogs (if MFA is configured).
$tenant_id = "00000000-0000-0000-0000-0000000000000"
$client_id = "00000000-0000-0000-0000-0000000000000"
$authParams = #{
ClientId = $client_id
TenantId = $tenant_id
Interactive = $true
}
$auth = Get-MsalToken #authParams
$auth

Teams PowerShell: Access token validation failure

I am trying to create a team with the new Teams Powershell. Looks like everything is working, until I try to use my service account instead of my own.
The code below is working, if I replace the $credential line and use my own credentials. If I use the automation account, then I got this:
New-Team : Error occurred while executing
Code: InvalidAuthenticationToken
Message: Access token validation failure.
I tried searching for this error message, but I only found Graph API samples, that happen behind the scenes of the Teams PowerShell. I also tried other scripts, like PnP, they all work fine with the same automation account. Is this a bug in the Teams API self or can I do something on my side?
$credential = Get-AutomationPSCredential -Name 'provisioning'
$connection = Connect-MicrosoftTeams -Credential $credential
$t = Get-Team -DisplayName "TEST"
Assuming your service account has proper privileges to create channel.
Reference: https://learn.microsoft.com/en-us/graph/api/team-put-teams?view=graph-rest-1.0
If you reckon you have proper privileges to create teams and channels then make sure you give full scope to the service account
Connect-PnPOnline -Scopes "Group.ReadWrite.All"
Hope it will give you some idea to solve the error. Thanks

Using Powershell to get Azure AD Token (jwt)

I am trying to get a jwt token from AAD using Powershell using Username/Password authentication.
I am writing a powershell script that will to call an API using a bearer token. What I have works if I copy & paste the token from an SPA that uses the API. I am looking for a way to retrieve the token from my powershell.
This looks really promising: https://github.com/Azure-Samples/active-directory-dotnet-native-headless/blob/master/TodoListClient/Program.cs
I feel like I'm smacking my head against a wall trying to create a 'UserPasswordCredential' object. Any clues to how I can do this would be super-helpful.
I have Add-Type-ed:
- Microsoft.IdentityModel.Clients.ActiveDirectory.dll
- Microsoft.IdentityModel.Clients.ActiveDirectory.platform.dll (adds nothing?)
- Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll
- Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll
The docs page for 'UserPasswordCredential' :
https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.userpasswordcredential
It should be in one of the first two dlls
This, under 'Constraints & Limitations', makes me think it may not actually be possible from powershell:
http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/
Looking at the code below, the first acquire token succeeds, the second fails - possibly/probably because $cred is a UserCredential not a UserPasswordCredential.
Is is possible to do this with powershell?
Finally, on a totally different track, how do I find the values for redirectUri and resourceAppIdURI that my application needs? When I look in the AAD console, and browser to my Enterprise Application, I can find the AppId (which I can use as $clientId).
I'm not sure the redirectUri is strictly necessary for me as all I really want is the token, but I can have a good guess at what it should be.
When I try to call the first AquireToken method (without $cred) using my app details, it fails with this message:
Exception calling "AcquireToken" with "4" argument(s): "AADSTS50001: The application named https://myappwithapi/Login was not found in the tenant named me.onmicrosoft.com.
Is it possible for me to find the require value for resourceAppIdURI by looking in my azure portal?
'https://myappwithapi/Login' is from my azure portal > enterprise apps > [app' > properties > HomepageUrl
code:
#setup
$TenantName = "mme.onmicrosoft.com"
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2" # Microsoft
$clientId = "03faf8db-..........................." #
$username = "me#me.onmicrosoft.com"
$password = Read-Host -AsSecureString -Prompt "Enter Password"
# add dlls
$adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
$adalplatform = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.platform.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalplatform) | Out-Null
#prep request
$redirectUri = "urn:ietf:wg:oauth:2.0:oob" # Microsoft
$resourceAppIdURI = "https://graph.windows.net"
$authority = "https://login.windows.net/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
# Get Token prompting for creds
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Always")
$authResult
# Get the cred
$cred = New-Object -TypeName 'Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential' -ArgumentList $username, $password
#$cred = New-Object -TypeName 'Microsoft.IdentityModel.Clients.ActiveDirectory.UserPassCredential' -ArgumentList $username, $password
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $cred)
$authResult
This post has more the one question in it.
Your base use case 'Using Powershell to get Azure AD Token (jwt)' is a common one and there are several samples and pre-built examples to leverage. For example:
https://github.com/pcgeek86/AzureADToken
A PowerShell module that allows you to get a JSON Web Token (JWT) from Azure Active Directory (AAD).
https://gallery.technet.microsoft.com/Get-Azure-AD-Bearer-Token-37f3be03
This script acquires a bearer token that can be used to authenticate to the Azure Resource Manager API with tools such as Postman. It uses the Active Directory Authentication Library that is installed with the Azure SDK.
See if those two resources resolves your use base line use case.
As for this...
"Is it possible for me to find the require value for resourceAppIdURI by looking in my azure portal?"
You can do this via a remote PowerShell logon to AzureAD. Install the AAD PowerShell module.
https://learn.microsoft.com/en-us/powershell/azure/overview?view=azurermps-5.1.1
https://msdn.microsoft.com/en-us/library/dn135248(v=nav.70).aspx
Download and install MSOL. Sign in with the MSOL
https://www.microsoft.com/en-US/download/details.aspx?id=39267
The Microsoft Online Services Sign-In Assistant provides end user sign-in capabilities
and use the built-in cmdlets to pull your information from your organization settings, and or hit the MSGraph API and query.
https://learn.microsoft.com/en-us/powershell/azure/active-directory/install-adv2?view=azureadps-2.0
You can use the Azure Active Directory PowerShell Module Version for Graph for Azure AD administrative tasks
As for this one:
"how do I find the values for redirectUri and resourceAppIdURI that my application needs?"
This is in your app registration section of your portal. The developer team provide the redir uri not Azure. It's part of the registration process all else is generated by Azure App Reg process.
The app registration process is here and of course you are someone else had to register this app in AzureAD, and thus can retrieve it at any time.:
https://blogs.msdn.microsoft.com/onenotedev/2015/04/30/register-your-application-in-azure-ad
Any registered apps and their details can be retrieved using...
Get-AzureADApplication
Get-AzureADApplication | Select -Property *
(Get-AzureADApplication).ReplyUrls
Get-AzureADApplication | Select -Property AppID, DisplayName,ReplyUrls
https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureadapplication?view=azureadps-2.0

Deleting Gmail Emails via Google API using Powershell v2.0

$user = "example#gmail.com"
$pass= "examplepassword"
$secpasswd = ConvertTo-SecureString $user -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($pass, $secpasswd)
Invoke-RestMethod 'https://www.googleapis.com/gmail/v1/users/me/messages/0' -Method Delete -Credentials $cred
So, my problem here is twofold.
I originally tried using Invoke-WebRequest to delete gmail emails via the Google API with a http delete request. However, this did not work because Powershell 2.0 does not support Invoke-WebRequest.
Thereafter, I turned to attempting to utilize Invoke-RestMethod after experimentation with IMAP and POP3, which both required external dependencies (Adding .dlls to the machines I am working with is not optimal).
Therefore, if someone could show me the appropriate way to delete an email via the Google API in Powershell, I would appreciate it. I have provided some sample code as to what I am working with above. Please excuse any mistakes it may contain, as I am relatively new to Powershell, and my experience remains limited in working with RESTful services.
The GMail API is going to require Oauth2 authentication unless this is a gsuit / domain admin / GMail account in which case you can use a service account for authentication. In either case you cant use login and password.
My powershell knowledge is very limited have you considered doing this directly though the mail server IMAP and SMTP and not using the API. No idea if that's possible or not with powershell
Update:
I was able to do it using Invoke-WebRequest you will still need to get an access token first.
Invoke-WebRequest -Uri "https://www.googleapis.com/gmail/v1/users/me/messages/0?access_token=$accesstoken"-Method Get | ConvertFrom-Json
seams to also work
Invoke-RestMethod -Uri "https://www.googleapis.com/gmail/v1/users/me/messages/0?access_token=$accesstoken"-Method Get
Put up a the code for OAuth on GitHub if your interested: Google Oauth Powershell