Configurable token lifetimes in Azure Active Directory - powershell

I could not assign TokenLifetimePolicy Azure AD application policy from PowerShell. I had an error BadRequest : Message: Open navigation properties are not supported on OpenTypes.Property name: 'policies
I am trying to implement token expiry time from Configurable token lifetimes in Azure Active Directory
See screenshot below, any useful links and solutions on the AzureAD cmdlet Add-AzureADApplicationPolicy are welcome

I made it work by only using New-AzureADPolicy cmdlet and setting -IsOrganizationDefault $true not $false. The effect takes a while for you to see it. So wait for about 30 minutes to an hour (I don't know how long exactly). After that your new policy will be created and applied. Also remember that this is PowerShell, so no whitespaces in the cmdlet.
Example:
New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"02:00:00","MaxInactiveTime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') -DisplayName "PolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
Multi-Line version:
New-AzureADPolicy -Definition #(
'
{
"TokenLifetimePolicy":
{
"Version": 1,
"AccessTokenLifetime": "02:00:00",
"MaxInactiveTime": "02:00:00",
"MaxAgeSessionSingleFactor": "02:00:00"
}
}
'
) -DisplayName "PolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
Microsoft may fix the issue with IsOrganizationDefault $true. Read more on this in the question: Azure AD Configurable Token Lifetimes not being Applied.

I test this quite a bit for my customers. I run into issues like this every now and then due to not on the latest version of PowerShell.
get-module
Latest Version 2.0.0.114 at the moment for AzureADPreview (V2)
Instructions to download here
There was an issue with -IsOrganizationDefault $true as Seth has pointed out.
Another issue I've found is having multiple versions of PowerShell on your system and it's loading the wrong one that doesn't have the updated bits. I hit this last Friday - I had to wipe everything and reinstall - then it fixed it.
Also -
There is a difference between:
Add-AzureADApplicationPolicy
and
Add-AzureADServicePrincipalPolicy
One is for an application object and the other is for a ServicePrincipal. If you are applying it to say, a SAML-Based application, then you should apply it to the ServicePrincpal.
Note: There is a different ObjectID for the application object and the servicePrincipal object. Don't get these confused. For an experiment, run the two cmds against your application:
Get-AzureADServicePrincipal -SearchString <name of app>
Get-AzureADApplication -SearchString <name of app>
If you grab the wrong ObjectID - no go when you go to apply the policy
The sequence for these Policies are: ServicePrincipal -> Application -> Tenant (organization)

Was the application created in B2C portal?
Assuming the answer is yes, this behavior is expected:
Microsoft has 2 authorization end points, V1 and V2.
B2C portal creates V2 apps. The token lifetime setting from powershell probably only works against the V1 apps.
There are settings on the b2c blade to change this.
The other option is to create an app from the azure active directory blade(as opposed to the b2c blade). Then you can set the token life time using powershell.

Related

Is there an alternative way for Set-UnifiedGroup -UnifiedGroupWelcomeMessageEnabled?

A couple of years ago, we made a provisioning script which creates a unified group with PnPPowerShell. While there was no other way to disable the welcome message for new group members, we had to connect with Exchange and disable the welcome message with Exchange Online PowerShell using Set-UnifiedGroup -UnifiedGroupWelcomeMessageEnabled.
Due to changed requirements of the customer as a result of the status of the legacy auth at Microsoft, legacy authentication will no longer be available soon and should be disabled on our customer's environment asap.
And now the trouble begins. As we have an older environment with Exchange Online PowerShell V2 running on PowerShell 5, we can't connect with -ManagedIdentity but we would have to connect with a certificate to run the unattended script.
Now we encountered the next problem: according to this documentation at Microsoft Learn, the commandlet Set-UnifiedGroup will not work with app-only authentication for unattended scripts in Exchange Online PowerShell V2.
So we had a look into the MS Graph API documentation to update groups to find out if there is a property to achieve the disabling of the welcome messgae, but it seems that there is none.
Long story short, is there any way to update the group through an unattended script without legacy authentication, using Exchange Online PowerShell V2 on PowerShell 5? Upgrading PowerShell and the Exchange module would affect a bunch of other provisioning scripts where we are currently already able to connect with the -ManagedIdentity parameter.
It seems to me that resourceBehaviorOptions property on group resource object is what you are looking for.
It specifies the group behaviors that can be set for a Microsoft 365 group during creation. This can be set only as part of creation (POST) (New-MgGroup powershell cmdlet).
One of possible values for resourceBehaviorOptions is WelcomeEmailDisabled. If the value is specified then welcome emails are not sent to new members.
Example:
Import-Module Microsoft.Graph.Groups
$params = #{
Description = "My new group"
DisplayName = "Groupxxx"
GroupTypes = #(
"Unified"
)
MailEnabled = $true
MailNickname = "library"
SecurityEnabled = $false
ResourceBehaviorOptions = #(
"WelcomeEmailDisabled"
)
}
New-MgGroup -BodyParameter $params

Azure AD V2 MFA support

I am looking for support on the v2 Azure AD cmdlets, specifically assigning an MFA policy on a directory user using Set-AzureADUser. So How can I enable MFA for Azure AD V2 powershell ?
I do not believe it is possible to set MFA on a user using the V2 version of the AAD PowerShell Module. This is because the property does not appear to be exposed via the AAD Graph API yet.
Instead, you need to use the older V1 version of the AAD PowerShell Module (MSOL Powershell). There is documentation online that shows how to do this, like this one.
$auth = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$auth.RelyingParty = "*"
$auth.State = "Enabled"
$auth.RememberDevicesNotIssuedBefore = (Get-Date)
Set-MsolUser -UserPrincipalName <UserPrincipalName> -StrongAuthenticationRequirements $auth
There are a bunch of warning related to setting MFA in this manner, as the user will additionally need to go and set up their MFA settings through the MFA UI. Please make sure you test the end to end flow here before you do this on many users in bulk.

azure AD powerShell edit manager

I have written a DotNet Forms applications which uses PowerShell automation to create and modify users in On-premise AD, On-premise Exchange, Azure AD and O365 to match records provided by HR. This has been in use by a customer for a few years and works fine.
The code makes use of the Azure Active Directory Module for Windows PowerShell (MSOnline - MSOL) to view and edit users in Azure AD. I originally used MSOL version 8073.4 but I've since upgraded to MSOL version 1.1.166.0
(see http://social.technet.microsoft.com/wiki/contents/articles/28552.microsoft-azure-active-directory-powershell-module-version-release-history.aspx)
For example I'd use the following PowerShell to modify a user's title:
Import-Module MSOnline
$Cred = Get-Credential
Connect-MSOLService -Credential $Cred
Set-MSOLUser -UserPrincipalName Santa#northpole.com -Title 'Deliverer of presents'
Everything was fine until I was asked to extend the code to update each Azure AD user's "Manager ID" attribute. Easy I thought! I just need to update the user's "Manager ID" field (which is the ObjectID of the manager's Azure AD account) just like I update the title.....
Er, no. I can't find any way to change the manager field. I've gone over and over the MSDN documentation and cannot find any method to do this:
So I looked at the new v2 Azure AD modules which are in preview at the moment (mentioned in the above release history URL) and can be downloaded from the PowerShell Gallery (search for "AzureADPreview").
These are ultimately going to replace the old MSOL cmdlets and look very similar to the existing Azure PowerShell modules (for creating VMs etc).
This does provide support for setting a user's "manager ID" via the command
Set-AzureADUserManager
and I've tried this and it works, so I thought I'd update my application to use the new v2 APIs instead of the v1 APIs (MSOL).
Unfortunately I found that the
Set-AzureADUser
command (used to set attributes like job title) is completely broken in v2.0.0.1 and fails with the error
"Exception has been thrown by the target of the invocation"
for any combination that I try. I've reported this to the developers via the PowerShell gallery.
Luckily I found that the previous version 1.1.167.0 of these modules works fine so I'm using that version and can now successfully create users, modify users, configure the user's "Manager ID" but I cannot work out how to set licenses (e.g. O365_BUSINESS_PREMIUM). The documentation for the command Set-AzureADUserLicense is pretty much non-existent and I've been unable to work out how to use it.
I think I need to do the following:
# Create an object which contains the individual license 'x' I want to add
# The available license SkuIDs can be read from Get-AzureADSubscribedSku
$MySingleLicenseToAdd = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$MySingleLicenseToAdd.SkuID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Create a licenses object which is assigned the individual licenses I want to add or remove
$MyLicensesToAddOrRemove = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$MyLicensesToAddOrRemove.AddLicenses = $MySingleLicenseToAdd
$MyLicensesToAddOrRemove.RemoveLicenses = $Null
# Perform the license action against the specified user 'y'
Set-AzureADUserLicense -ObjectId 'yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyy' -AssignedLicenses $MyLicensesToAddOrRemove
but it fails on the second line of code saying that "SkuID" is a read-only field.
So I can't use the V1 (MSOL) APIs because I cannot find a way to update the user's "Manager ID" field.
I can't use the V2 APIs because I cannot find a way to assign licenses (and it's in preview so not a great idea to use in live)
My current plan is to go back to using the V1 APIs but then make use of the V2 APIs to update the "Manager ID" field only, but this is hardly an ideal solution (because I'll be signed into Azure twice with two different APIs) so I was wondering if anyone could provide any suggestions?
My preference would be to use the v1 (MSOL) APIs to update the
"Manager ID" field.
My second preference would be to use the v2 APIs and learn how to assign licenses.
My third preference is anything else ;)
I have read one article about using the REST APIs directly, but that was WAY heavy and I'd prefer to avoid and stick with an Azure PowerShell API if possible.
Sorry about the looooong question, but I was trying to provide some context as to why I'm trying to use the V2 APIs.
Update (23/09/2016):
AzureADPreview 2.0.0.2 was just released and it fixes the problem with Set-AzureADUser :) but unfortunately partially breaks Set-AzureADUserManager :(
Same problem with licenses with this new version
Here is an example of how you can use the Set-AzureADuserLicense cmdlet to set licenses for a user.
Please let me know if this clarifies.
# Get the License SkuId from a template user that we want to apply to the new user
$licensedUser = Get-AzureADUser -ObjectId "TemplateUser#contoso.com"
# Get the new User we want to apply the license too
$user = Get-AzureADUser -ObjectId "newuser#contoso.com"
# Create the new License object
$license = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$license.SkuId = $licensedUser.AssignedLicenses.SkuId
# Create the Licenses Table and add the license from above
$licenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$licenses.AddLicenses = $license
# Apply the license to the new user
Set-AzureADUserLicense -ObjectId $user.ObjectId -AssignedLicenses $licenses
Thanks for replying. Rob.
The code you supplied is the same as what I was trying (see the code in my original question) with the exception that you retrieve the SkuID from an existing user.
Since two new versions of AzureADPreview have since been released (2.0.0.7 and 2.0.0.17), this prompted me to try again with the new versions of AzureADPreview and also the original versions that were available when I originally posted.
My results are as follows:
2.0.0.1: Doesn't work. Read-Only error.
2.0.0.2: Doesn't work. Read-Only error.
2.0.0.7: Works
2.0.0.17: Works
So basically it was a fault in the original versions of AzureADPreview but Microsoft have since fixed it.
All working now.

Can't get Move-AzureResource working

I'm trying to move some of my resources (Azure Web Apps, Azure SQLs, Redis caches) from one resource group to another. I'm using the Azure Resource Manager PowerShell cmdlets.
Here's what I've tried:
PS C:\> Move-AzureResource -DestinationResourceGroupName NewResourceGroup -ResourceId "/subscriptions/someguid/resourceGroups/Default-Web-WestEurope/providers/Microsoft.Web/sites/somesite"
Or:
PS C:\> Get-AzureResource -ResourceName somesite | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
Or:
just Move-AzureResource, hitting enter and supplying the parameters one by one.
None of the commands seems to work. They just don't do anything. No error, no output.
When I changed the debug preference to $DebugPreference = "Continue" I got only the following:
DEBUG: 12:16:06 - MoveAzureResourceCommand begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 12:16:06 - using account id 'my#account.tld'...
Please note that I'm able to create a new resource group (New-AzureResourceGroup), list resource groups (Get-AzureResourceGroup), list resources (Get-AzureResource), etc.
Note: you have to call Switch-AzureMode AzureResourceManager before you can use the cmdlets. The authentication is done by Add-AzureAccount.
Articles I've been referring to:
Moving resources between Azure Resource Groups
Move-AzureResource
Using Azure PowerShell with Azure Resource Manager
GitHub - Using Azure PowerShell with Azure Resource Manager
Reading this azure forum it looks like they have implemented the cmdlet but not all resources support being moved yet.
We have released a new powershell cmdlet to move resources across resource groups. Not all resources have support yet, but the "main" ones do like hosted services, virtual machines & storage accounts.
Looking back at the example I was following, this does only use VM's. So based on this I think websites aren't supported yet. That fact that no error or warning is returned for unsupported resources is a bit poor.
Though not all resources are currently supported, I understand the current version - 0.9.1 - does have a bug which means that even a supported resource may not be moved with the symptoms as seen by the author of the question. I understand this is being worked on for the next release, but in the interim (as a temp. work around) the previous powershell cmdlets release of 2 versions ago should work fine. https://github.com/Azure/azure-powershell/releases
The original issue is fixed in the 0.9.4 release. I just tried and it works.
FYI. To move a VM using Move-AzureResourceGroup you need to move the containing cloud service and all its VMs at the same time. For example:
Get-AzureResource -ResourceGroupName OriginalResourceGroup | where { $_.ResourceType -match 'Microsoft.ClassicCompute' } | Move-AzureResource -DestinationResourceGroupName NewResourceGroup
By default, the resources in a cloud service are put in a resource group with the same name as the DNS name of the cloud service.
For some reason, Azure PowerShell Version 1.0 has trouble moving over web apps from one Resource Group to another. If you follow the instrctions below, you will be able to move the web app over via powershell.
Download Azure PowerShell Version 1. The below instructions only work for this version. Type the commands below in order.
1) **Login-AzureRmAccount** (a login window will pop up asking for your azure credentials, type them in)
2) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName"** (if you are moving over a website, you will see 2 files, you need the one that is a resource type of Microsoft.Web/sites)
3) **Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
4) Assign value 3 to a variable of your name choice. I Chose $a, so **$a = Get-AzureRmResource -ResourceGroupName "NameOfResourceGroup" -ResourceName "WebAppName" -ResourceType "Microsoft.Web/sites"**
5) **Move-AzureRmResource -DestinationResourceGroup "DestinationResourceGroup" -ResourceId $a.ResourceId**
6) It will ask you if you are sure type "Y" and hit enter.

Add-AzureAccount : Index was out of range. Must be a non-negative and less than the size of the collection

On 4th of August a new version of the Azure powershell module (0.8.7.1) was released. In it is the ability to create credentials which you could then pass to the Add-AzureAccount function. Add-AzureAccount allows you to pull in an account to work with in the current PowerShell session.
$userName = "buildmaster#someaccount.onmicrosoft.com"
$securePassword = ConvertTo-SecureString -String "somepassword." -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
Add-AzureAccount -Credential $cred
This allowed me to get away from a popup window or messing with a settings file.
It seems to have stopped working! Both Add-AzureAccount (which pops up a window) and the credential based way. They now return an index was out of range issue.
Add-AzureAccount : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
At S:\QA\Azure Scripts\cm-azure-helpers.psm1:1128 char:5
+ Add-AzureAccount
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureAccount], ArgumentOutOfRangeException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
Digging deeper with Fiddler shows that the OAuth call to the back end service seems to work. I get a token returned. But then I also get a 302 in the middle of the process stating that the page has moved. I don't know if that redirect was there when it was working previously or not.
Has anyone else experienced the Add-AzureAccount function just stop working like this? And more importantly - have you found a way around it?
Update - More info
I have now tried on several boxes under different azure accounts and seem to have the same results. I get a valid auth token returned with a redirect in the middle (not sure if that is an issue or not) and then get the index was out of range.
I have done this with the following variations:
PS:3 Azure Module: 0.8.6
PS:3 Azure Module: 0.8.7
PS:4 Azure Module: 0.8.6
PS:4 Azure Module: 0.8.7
I know exactly what caused this error for me, and how I worked around it (I thought I was the only one who had seen this :))
What had happened is that I had accidentally added a bogus/empty subscription to my account. And this empty subscription had been set to my "default" subscription.
Run "get-azuresubscription -default" to see what your default subscription is. You can then "remove" any junk subscriptions using "remove-azuresubscription" command.
You can then of course set a new azure subscription for your "default" using PS.
I actually reported this to the Azure PowerShell team now to get a better error message during this scenario.
Hopefully this solved your problem, it's possible other errors manifest the same error message.
If you do a fiddler trace, you should see that right after the login call (where PowerShell passes in your username/password, there should be 1 or multiple calls to GET /subscriptions.
Check the response to see whether there is anything suspicious there. Like, any of them return an empty body, empty array, subscription with id, name, etc..
I had a similar problem recently. The "fix" was for me was to delete the files at C:\Users[username]AppData\Roaming\Windows Azure Powershell (esp. the WindowsAzureProfile.xml file). The next time I ran Add-AzureAccount, the necessary files were created and all was well.
Please use:
Add-AzureRmAccount -SubscriptionId "id";
for login