How can I create an Azure AD Application Key? - powershell

Is it somehow possible to create an Azure AD Application Key via PowerShell?
I could not really find any working solution. Currently I have this piece of code:
$appName = "myAppName"
$password = "myPassword"
$app = New-AzureRmADApplication -DisplayName $appName -HomePage "https://$appName" -IdentifierUris "https://$appName" -Password $password
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName "Data Factory Contributor" -ServicePrincipalName $app.ApplicationId
This all works fine so far but I also need to create a Key for the app for clients to actually access it. In the Azure portal this would be under MyDirectory --> App registrations --> myAppName --> Settings --> Keys
also I am not quite sure what the Password for the application is actually used for?!

OK, I found this blog post and it seems to solve my issue:
https://www.sabin.io/blog/adding-an-azure-active-directory-application-and-key-using-powershell/

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

Partner Central rest api 401 unauthorized access

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.

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

How to add an application from the Azure AD Gallery Programmatically

How do I add an application from the AAD Gallery programmatically and configure it? I checked AAD Powershell commands but I could not find out how to use it to provision a pre-integrated applications from the Azure AD gallery. There is the New-AzureRmADApplication -DisplayName "NewApplication" -HomePage "http://www.microsoft.com" -IdentifierUris "http://NewApplication" for example but not an Add-AzureRmADApplication or similar. The application I need is already available under the "Developer Services" category in the AAD Applications Gallery and all I need is to add it and configure its Single-sign on and Provisioning attributes. Is that even possible or do I have to create a new app? Even if I created a new application how do I configure it past the just adding the HomePage and IdentifierUris parameters which is all I can do using the New-AzureRmADApplication cmndlt?
Any help would be appreciated. Thank you
There is currently no way to configure the applications from the AAD Application Gallery programmatically. You can refer to the following post:
https://social.msdn.microsoft.com/Forums/en-US/42f262e2-150e-48bd-a741-cbabf42fcf77/how-to-add-and-configure-aad-application-from-the-gallery-programatically?forum=WindowsAzureAD
In case anyone come's across this question again, this is now possible, with the AzVm modules, instead of AzRm.
First you get the "Gallery Application Version"
$galleryApp = Get-AzGalleryApplicationVersion -GalleryName $GalleryName `
-GalleryApplicationName $AppName `
-ResourceGroupName $ResourceGroupName
Then create a new app instance for your current PowerShell Session
$appInstance = New-GalleryApplication -PackageReferenceId $galleryApp.Id
You'll also need to set the order parameter after you create the instance. There's no parameter to set it when it's defined.
$appInstance.Order = $int32Value
Finally, add the application to your Virtual Machine
Add-AzVmGalleryApplication -VM $VirtualMachineObjet `
-GalleryApplication $appInstance
-ResourceGroupName $ResourceGroupName
Once the application(s) are added, you need to push the update with "Update-AzVm", otherwise they won't actually deploy.
Here's the full example:
$galleryApp = Get-AzGalleryApplicationVersion -GalleryName $GalleryName `
-GalleryApplicationName $AppName `
-ResourceGroupName $ResourceGroupName
$appInstance = New-GalleryApplication -PackageReferenceId $galleryApp.Id
$appInstance.Order = $int32Value
Add-AzVmGalleryApplication -VM $VirtualMachineObjet `
-GalleryApplication $appInstance `
-ResourceGroupName $ResourceGroupName `
-Order $int32Value
Update-AzVm -ResourceGroupName $ResourceGroupName -VM $VirtualMachineObject

AzureAD powershell New Service Principal

How do you set the Reply URL for a service principal with powershell.
The following doesn't commands don't add anything to that field when I check on the management portal.
$aa = new-AzureADApplication -DisplayName "Name" -HomePage "addr" -IdentifierUris "addr"
new-AzureADServicePrincipal -ApplicationId $aa.ApplicationId
..... setting up the roles and etc.
The IdentifierUris seem to only fill the APP ID URI. It takes an array but when I do something like this, azure responds with an internal error:
Either
$arr = #("addr1","addr2")
New-AzureAdApplication -IdentifierUris $arr
or
New-AzureAdApplication -IdentifierUris (,$arr)
or
New-AzureAdApplication -IdentifierUris #("addr1","addr2")
Is it possible to set this field through powershell?
I don't know of a way to do it with the Azure PowerShell modules, but you can do it with the Set-MsolServicePrincipal cmdlet in the Azure AD (aka MSOnline) module. Reply URLs can be managed via the Addresses collection.
Example (from https://gist.github.com/rytmis/4178996):
$addresses = $principal.Addresses
$addresses.Add((New-MsolServicePrincipalAddresses -Address http://localhost:81))
$addresses.Add((New-MsolServicePrincipalAddresses -Address http://my-deployment-endpoint.cloudapp.net))
Set-MsolServicePrincipal -AppPrincipalId $appPrincipalId -Addresses $addresses
Edit (some background info)
Applications and Service Principals are separate but related entities. (This article explains the relationship between the two).
When you create an application via the Azure AD portal, it creates both the application and the service principal. To get the same result from PowerShell, you have to create both objects.
# Create the application object
$azureAdApplication = New-AzureRmADApplication -DisplayName "<Your Application Display Name>" `
-HomePage "<https://YourApplicationHomePage>" `
-IdentifierUris "<https://YouApplicationUri>"
# Create the corresponding service principal
New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
Application/Service Principal combinations created this way should show up in the portal, and can be used the same way as those created in the portal.