Powershell command to find access and refresh token time - azure

In the past we configured token lifetime for access and refresh tokens but now i would like to find the time line set in the past.
I found PS commands to change the token lifetime but not able to find the command to validate it.
Is there a powershell command which i can run to find the access and refresh tokens lifetime set in Azure AD for the portal and applications?

I suppose you configured the token lifetime with azure ad policy, if so, you could try the command as below, make sure you have installed the AzureADPreview powershell module.
Sample:
Get-AzureADPolicy - Get all the TokenLifetimePolicys in your AAD tenant :
Get-AzureADPolicy | Where-Object {$_.Type -eq 'TokenLifetimePolicy'} | ConvertTo-Json
Get-AzureADServicePrincipalPolicy - Get the policy which has been assigned to the service principal :
Get-AzureADServicePrincipalPolicy -Id "<object id of service principal>" | ConvertTo-Json
Get-AzureADApplicationPolicy - Get the policy which has been assigned to the AAD application:
Get-AzureADApplicationPolicy -Id "<object id of application>" | ConvertTo-Json
For more details, refer to this doc - Configurable token lifetimes in Azure Active Directory (Preview).

Related

Azure - get deleted users - Using Get-AzureADUser

I'm hoping to use the updated graph powershell commands to be able to pull more information on deleted users.
I'm trying to use:
Get-AzureADUser -Filter "aad.IsDeleted eq 'True'"
but it returns the error:
The child type 'aaad.IsDeleted' in a cast was not an entitity type.
Ho do I filter for deleted accounts, if possible, so that I can also do a select to include additional parameters / attributes?
I'm hoping to be able to know when an account was deleted, a description, etc.
Moving some users to cloud only so we need to move them in AD to a container that is excluded from AD Connect. Then need to use a script to undelete them and validate licenses are still in use.
I know with
get-MsolUser -ReturnDeletedUsers
works, however I haven't been able to figure out how to return additional values / parameters / attributes.
It doesn't appear that Get-AzureADUser or Get-AzADUser have a way of filtering or returning deleted users. You can't even use -Filter as the property is not returned from the API call.
You can however workaround this slightly and call the API directly.
$result = Invoke-AzRestMethod -Uri 'https://graph.microsoft.com/beta/directory/deleteditems/microsoft.graph.user'
$jsonOutput = $result.content | ConvertFrom-Json
$jsonOutput.value | Select-Object id, displayName, mail, deletedDateTime
There are a couple of examples on github where people have written functions to assist with making those calls:
https://github.com/Azure/GuardrailsSolutionAccelerator/blob/0f3f4994c03d8e47d7d67bd790ba3b290f37560a/src/GUARDRAIL%202%20MANAGEMENT%20OF%20ADMINISTRATIVE%20PRIVILEGES/Audit/Check-DeletedAndDisabledUsers.psm1
and
https://github.com/Panzerbjrn/AzureGraphApiHelper/blob/4cd2dcd1067bdabd349b044f1760bb958d54179d/AzureGraphApiHelper/Functions/Get-AGDeletedUsers.ps1
• You can surely get all the details of the deleted Azure AD user accounts from your tenant through the below command. Also, you can use filter and attributes as shown below along with this command for sorting out specific details for a particular deleted user account: -
Command: -
Get-MsolUser -ReturnDeletedUsers -MaxResults 50 -EnabledFilter All | Export-Csv -Path C:\Users\v-kartikb\Downloads\Reatapp\delete4.csv ’
Output: -
Similarly, if you want to get any information regarding a specific user or search a user ID based on the search string, then please refer to the below commands: -
Get-MsolUser -ReturnDeletedUsers | FL UserPrincipalName,ObjectID
Get-MsolUser –ReturnDeletedUsers –SearchString <User UPN>| FLUserPrincipalName,ObjectID
Also, do ensure that you will have to sign into Microsoft Office 365 service for executing the above commands successfully by executing the below command successfully: -
Connect-MsolService
Also, you can get the details of any deleted user if you have the object ID with you by executing the below Azure AD command through powershell: -
Connect-AzureAD
Get-AzureADMSDeletedDirectoryObject -Id <ObjectID>
Output: -
Please find the below link for more details regarding the above commands: -
http://ajaxtechinc.com/question/manage-delete-users-office-365-recycle-bin/
This can be accomplished using the graph api and the Azure CLI for auth
$deletedUsers = az rest `
--method "GET" `
--url "https://graph.microsoft.com/v1.0/directory/deletedItems/microsoft.graph.user" `
--headers "Content-Type=application/json" | ConvertFrom-Json

What permissions are needed to read /write external collaboration policies?

I've written a powershell script that allows me to query azure for my azure ad policies like this:
Connect-AzureAD
$currentpolicy = Get-AzureADPolicy -All $true | ?{$_.Type -eq 'B2BManagementPolicy'} | select -First 1
$currentpolicy
$newPolicyValue = #("{`"B2BManagementPolicy`":{`"InvitationsAllowedAndBlockedDomainsPolicy`":{`"AllowedDomains`": [`"a.com`",`"b.org`",`"c.org`",`"d.com`"],`"BlockedDomains`": []}}}")
}
#update existing. This works. tested.
Set-AzureADPolicy -Definition $newPolicyValue -Id $currentpolicy.Id
This works because I'm signing in with an account that's got "owner" / global admin permissions. Now we wnat to try to figure out the specific permissions that are needed and just assign those to a new AD app registration.
I've created a service principal with a cert, and I changed my code like this:
Connect-AzureAD -TenantId $tid -ApplicationId $appid -CertificateThumbprint $thumb
$currentpolicy = Get-AzureADPolicy -All $true | ?{$_.Type -eq 'B2BManagementPolicy'} | select -First 1
$currentpolicy
I didn't add any specific permissions yet, and so when I run my script, I see the following error:
Get-AzureADPolicy : Error occurred while executing GetPolicies
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
InnerError:
RequestId: d88cd5d5-f8c9-4a4d-928b-986e0d5c25eb
DateTimeStamp: Thu, 16 Jun 2022 19:06:45 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
At C:\Users\me\Documents\src\test\setPolicy.ps1:4 char:18
+ $currentpolicy = Get-AzureADPolicy -All $true | ?{$_.Type -eq 'B2BMan ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-AzureADPolicy], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.MSGraphBeta.Client.ApiException,Microsoft.Open.MSGraphBeta.PowerShell.GetPolicy
Ideally, we want to use MS Graph permissions to do this. So i've been poking around in Azure, under the "API Permissions" for this application registration, but so far I haven't figured out which permission I need to add.
PS I know that the AzureADPreview and AzureAD is going away. But so far, it's the only way that I can automate these tasks. I have another stack question open about how to get this entire thing working via Graph
EDIT 1
I've tried the following permissions and none of them work so far...
EDIT 2
I've granted Policy.Read.All and now I can read the policies. Now it fails trying to update the existing policy.
It'd be nice to know specificially which read permission is needed so I don't have to grant all.
As far as write permissions, I've granted everything that comes up when I search for "policy" but none of them allow me to write!
EDIT 3
I've added the policy.readwrite.applicationconfiguration but that doesn't allow me to write. I'm still get the insufficient privleges error when I try to call Set-AzureADPolicy.
I don't know if you have found an answer, but as this is one of the first results that came up, I will add my findings.
I could get nowhere from giving specific permissions to the Service Principal but adding the Security Administrator role to the app did the trick. I didn't want to give the service principal so much access, but I tried a lot of roles and permission combinations, and none were sufficient.
Apparently, the documentation states that the least privileged role that is able to configure B2B external collaboration settings is the Global Administrator. Although for this case specifically, of changing the B2BManagementPolicy via PowerShell with a service principal, the Security Administration role was enough in my testing.
Looking at the actions that this role can perform I suspect it's because it has access to microsoft.directory/policies/basic/update, but I can't be sure.
Note: When adding a role to an App registration in Azure AD you need to search for its name when selecting the members, as they don't show by default.
Thanks for reaching out , with the help you read access , you will only able to get the data ,if you want to add or update you should have write permission as well , please add permission Policy.ReadWrite.ApplicationConfiguration and try again .
ref doc - https://learn.microsoft.com/en-us/graph/api/tenantappmanagementpolicy-update?view=graph-rest-beta&tabs=http
Edit 2
Update policy is available for PowerShell 2.0 preview
To update you need to use
Set-AzureADPolicy -ObjectId -DisplayName
To learn more about Set-AzureADPolicy, please checkout - https://learn.microsoft.com/en-us/powershell/module/azuread/set-azureadpolicy?view=azureadps-2.0-preview&viewFallbackFrom=azureadps-2.0
Thanks

Azure - MFA details of the users using service principal

Wrote the below script to get the MFA status for all admins.
Works well. But I want to run this using the credential of a service principal and looks like Connect-MsolService does not have an option to do that.
Alternatively, Connect-AzAccount has the option to do that but in Az Powershell I dont find a way to get the MFA details of the users.
Is there a way to get the MFA details of the user using service principal?
Connect-MsolService
$output_file_location = "c:\temp\azure_admins_mfa_status_"+$(get-date -f yyyy-MM-dd-HH-mm-ss)+".csv"
$admin_roles = "Company Administrator","Billing Administrator","Conditional Access Administrator","Exchange Service administrator","Helpdesk administrator","Password administrator","Security administrator","Sharepoint Service administrator"
# Gets all the members in the admin roles in the roles list above
# Gets the MFA status for each member
# Appends the below data points to a file specified in the $output_file_location variable
# DisplayName,E-mail,Role,MFA-Requirements, MFA-Methods, MFA-MethodsDefault
function get-mfs-status
{
foreach ($roleName in $admin_roles)
{
write-output $roleName
$members = Get-MsolRoleMember -RoleObjectId $(Get-MsolRole -RoleName $roleName).ObjectId
#write-output $members
foreach ($member in $members)
{
write-output $member.EmailAddress
}
foreach ($member in $members)
{
write-output $member
Get-MsolUser -UserPrincipalName $member.EmailAddress | select DisplayName, `
#{N='E-mail';E={$_.userPrincipalName}}, `
#{N='Role';E={$roleName}}, `
#{N='MFA-Requirements';E={(($_).StrongAuthenticationRequirements.state)}}, `
#{N='MFA-Methods';E={(($_).StrongAuthenticationMethods.MethodType)}}, `
#{N='MFA-MethodsDefault';E={($_.StrongAuthenticationMethods | where isdefault -eq 'true').MethodType}} `
| select DisplayName,E-mail,Role, MFA-Requirements, MFA-Methods, MFA-MethodsDefault| Export-Csv $output_file_location -Append `
}
}
}
get-mfs-status
• No, you cannot retrieve the MFA details of the users in an Azure AD using service principal through powershell because service principal is generated for an instance of Azure resource, not an identity which has already been assigned an Azure AD role regarding the scope that has been defined with it. Thus, as an identity though of an Azure AD administrator has the scope of the whole subscription which hosts multiple tenants of your organization, has been defined with some roles and assignments pertaining to that scope. You can create a service principal with that ID logged in to Azure Powershell for the scope of your signed in ID but cannot retrieve the MFA status of users in Azure AD because when you pass the service principal in a variable to pass it as a credential and log in to the Microsoft 365 online, it cannot actuate them to the identity credentials and M365 doesn’t consider it.
Also, to get the status of MFA details of the users, you must connect to MS Online, you cannot retrieve it through Azure AD. Even if you convert the service principal secret in plain text and pass it as a credential to connect to M365, it doesn’t consider it nor it actuates the credentials.
• Instead, if you log into Azure/M365 using your actual credentials, i.e., ID and password, you will be able to retrieve the details provided you have the required role assignments and access.
Reference link for service principal usage: - https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-6.6.0
It's beta but how about that:
https://learn.microsoft.com/en-us/graph/api/reportroot-list-credentialuserregistrationdetails?view=graph-rest-beta&tabs=http

Configuring Azure AAD token lifetime to 10mins using powershell doesn't work

I have followed below article for configuring azure aad token lifetime to 10mins
How can I configure the expiration time of an Azure AD access token (using ADAL)?
I have used command below for assigning policy to app
Add-AzureADApplicationPolicy -Id <ObjectId of the AAD Application> -RefObjectId <ObjectId of the Policy>
Policy created but not reflected on new tokens created. Token expiry still showing as 1 hour for new tokens.
As AdminOfThings said, this policy is applied to the web API. When the native app requests the web API as a resource, this policy is applied.
And you could try to set -IsOrganizationDefault as true to create a strict policy for a web API.
New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:10:00","MaxAgeSessionSingleFactor":"00:10:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
You should also check to see if a default policy exists too, as long as it is not overridden by a policy with a higher priority.

Cannot delete user in Azure B2C using Graph API

We are attempting to delete a user within Azure B2C by using the Graph API, but have had no luck up to this point. Documentation here suggests that it is possible:
https://msdn.microsoft.com/Library/Azure/Ad/Graph/api/users-operations#DeleteUser
We currently have no issues when it comes to creating/updating users, but when attempting a delete operation we get the following error:
Authorization_RequestDenied - Insufficient privileges to complete the operation.
I'm aware there are limitations to using the Graph API with B2C, but the documentation out there suggests this should not be one of them.
If you want to have enough privileges to Delete Users, you need to assign Company Administrators Role to your Service principal. You can refer to this document to do that.
Use AAD Powershell to Connect AAD:
Connect-AzureAD
Get the Role of Company Administrator:
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'}
Assign the role to your SP:
Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId $yoursp.ObjectId
Try to Get a new token and use it in the head to Delete the user again. Here is my result:

Resources