How to invite external users to a SharePoint site or Microsoft Team using Power Automate and Graph API

SharePoint and Microsoft teams services in Microsoft 365 makes it easier to share content or collaborate with external users who is outside your organization. A guest or external user is someone who do not have a school or work account with your organization, they can be your partner, vendor, customer etc. In this article let us see how to build a self-registration experience for external users with the help of Microsoft Forms & Power Automate to onboard them to a

  • SharePoint online site
  • Microsoft Team

Microsoft Form to collect details from External User:

To start building this experience, create a Microsoft form with the setting Anyone can respond and with fields (Name, Email address etc) to collect information from the external user to send invitation.

Azure Active Directory Application registration:

The next step after creating the form is to register an application in Azure AD with Microsoft graph API permission to send invitation to external user. After the app is registered obtain the client id, client secret & tenant id to be used in the Power Automate flow further down this article to generate the JSON webtoken to access Microsoft Graph API for sending invitation. Find below screenshot with the permission User.Invite.All added to the app. Keep in mind the permission requires Admin consent.

There is also delegated permission available for User.Invite.All.

Onboard External users to a SharePoint online site:

Once the Microsoft form is ready, we can start building the Power Automate flow which can send the email invitation to the external user and for granting access to the SharePoint site. The external sharing features of SharePoint Online enables users in your organization share content with people outside the organization. There is no limit to the number of guests you can invite to SharePoint sites as per this SharePoint online limits documentation. Find below steps to create the Power Automate flow with a custom approval on a Microsoft Team

Power Automate Flow:

Create an Automated flow with the trigger When a new response is submitted with the above form name selected on the dropdown and then add the action Get response details with the Response Id selected from the dynamic content for the trigger to get the form details submitted in the Microsoft form by the external user. Find screenshot below

Adaptive card for Teams Approval:

For the Approval in Microsoft Teams, I have used a custom card created from the Adaptive card designer with elements ColumnSet, TextBlock to display information submitted in the form & action button Approve and Reject to take further action by a Microsoft teams user to proceed with Invitation for the Guest account creation. Find screenshot below from the adaptive card designer

  1. After the card is designed, copy the card payload from the designer and go to the flow and then add the action Post adaptive card and wait for a response and make appropriate selection on the available fields as shown below
    • Post as: Flow bot
    • Post in: Channel
    • Message: Payload copied from designer. Replace the fields for usrName & userEmail selected from the dynamic content from the outputs of the action Get response details. The created on textBlock element has the flow expression formatDateTime(utcNow(),’g’) to display the current datetime information on the card.
  • Update Message: Custom message which appear after an action taken in Microsoft Teams
  • Team: Select the Team where you would like to post the card
  • Channel: Select the channel from the Microsoft Team where you would like to have the approval adaptive card posted

Card payload:

{
    "type": "AdaptiveCard",
    "body": [
        {
            "type": "TextBlock",
            "weight": "Bolder",
            "text": "Approval for adding the External User",
            "wrap": true
        },
        {
            "type": "TextBlock",
            "spacing": "None",
            "text": "Created Add flow expression to get current date",
            "isSubtle": true,
            "wrap": true
        },
        {
            "type": "ColumnSet",
            "columns": [
                {
                    "type": "Column",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": "Name:",
                            "wrap": true,
                            "size": "Medium",
                            "weight": "Bolder"
                        },
                        {
                            "type": "TextBlock",
                            "text": "Email:",
                            "wrap": true,
                            "weight": "Bolder",
                            "size": "Medium"
                        }
                    ],
                    "width": "stretch"
                },
                {
                    "type": "Column",
                    "width": "stretch",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": "usrName-Replace it from Microsoft Form",
                            "wrap": true
                        },
                        {
                            "type": "TextBlock",
                            "text": "userEmail-Replace it from Microsoft Form ",
                            "wrap": true
                        }
                    ]
                }
            ]
        }
    ],
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Approve",
            "id": "btnApprove"
        },
        {
            "type": "Action.Submit",
            "title": "Reject",
            "id": "btnReject"
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.0"
}
  1. The above adaptive card is used to get approval from the Organization teams user based on the information submitted by the external user in the Microsoft form to proceed with the next steps for sending the guest account invite. Now we will have to identify if the user has clicked the button Approve or Reject. This information can be easily obtained from the Outputs of the action.

Note: Adaptive card can also be sent using a Microsoft Graph API with the card payload in Attachments field

Adaptive card for Teams – Dynamic content Missing:

As of the time I am writing this article there is an issue in getting the output as dynamic content for the Post adaptive card and wait for a response action if there is dynamic content added on the JSON Payload (Name, Email from Forms). The fix is to run the flow till the post adaptive card action and take an action on Microsoft teams by clicking either Approve or Reject and then go to the Flow run from the history as shown below

From the above screenshot, we can see if the user has clicked the Approve or Reject button from the field submitActionId. To get this value in Flow, use the expression

outputs('Post_adaptive_card_and_wait_for_a_response').body.submitActionId

or

@outputs('Post_adaptive_card_and_wait_for_a_response')?['body/submitActionId']

Spaces in the name of the action is replaced with underscore.

To get the userPrincipalName, the expression is

outputs('Post_adaptive_card_and_wait_for_a_response').body.responder.userPrincipalName

or

@outputs('Post_adaptive_card_and_wait_for_a_response')?['body/responder/userPrincipalName']

To get the submitActionId, enter the expression outputs(‘Post_adaptive_card_and_wait_for_a_response’).body.submitActionId in the compose action, then add a condition control to decide action based on users approval

I have observed this issue occurs in other team’s adaptive card actions as well, the above fix should work. Now we can implement the logic to send the Guest Invitation using Microsoft Graph API. To send the invite, we will use the Azure AD application registered above.

Generate JSON Web token to Access Graph API:

Be ready with the ClientId, Client Secret and Tenant Id collected from the AD app registration you have done initially. The only authentication flow to generate a access token for application permissions is Client credentials.

To generate a token

  1. Store the Client Secret on a String variable or a compose action
  2. Make a HTTP request using the HTTP connector with the following details. Make sure to replace the string for tenantId, azureAdAppclientId and azureAdAppclientSecret

Add a HTTP connector action to the flow for making a POST request per the following information

HTTP Method: POST

URI: https://login.microsoftonline.com/yourtenantId/oauth2/v2.0/token

Headers: Content-Type: application/x-www-form-urlencoded

Body:

tenant=yourtenantId&client_id=azureAdAppclientId&client_secret=@{decodeUriComponent(variables('azureAdAppclientSecret'))}&grant_type=client_credentials&scope=https://graph.microsoft.com/.default

For the client secret make sure to URL encode using the expression encodeUriComponent(variables(‘clientSecret’)) else the request may fail due to the presence of special characters.

In the above screen, I have added a compose action to store the SharePoint site address to be used for granting the external user access to. To extract the token from the above request, add the parse JSON action with Content from the HTTP request body and the following schema

{
    "type": "object",
    "properties": {
        "token_type": {
            "type": "string"
        },
        "scope": {
            "type": "string"
        },
        "expires_in": {
            "type": "integer"
        },
        "ext_expires_in": {
            "type": "integer"
        },
        "access_token": {
            "type": "string"
        },
        "refresh_token": {
            "type": "string"
        }
    }
}

Include the access token when calling the Microsoft Graph API in the Headers section or raw as shown in the next section.

Send Invitation using Microsoft Graph API:

Before sending the invitation, validate if the user already exists in your organization AD tenant by using the email address of the external user with the help of the action Search for users as shown below

If there is null response for the action Search for users, then the user does not exist. This can be calculated using the expression length and by passing the value as a parameter, if it is equals zero then the external user does not exist. If the user already exists, we can directly proceed to granting the external user access to SharePoint.

Graph API to check if a guest user already exists:

https://graph.microsoft.com/v1.0/users?$filter=UserType eq ‘Guest’&$filter=mail eq exteruseremailaddress@domain.com’

or

https://graph.microsoft.com/v1.0/users?$filter=startswith(mail,’exteruseremailaddress@domain.com’)

Find below the Graph API endpoint http request details to invite the external user

Method: POST

URL: https://graph.microsoft.com/v1.0/invitations

Request Body:

{
  "invitedUserDisplayName": "External User Name",
  "invitedUserEmailAddress": "External User Email Address",
  "sendInvitationMessage": true,
  "inviteRedirectUrl": "SharePoint site URL or any URL",
  "invitedUserMessageInfo": {
    "messageLanguage": "en-US",
    "customizedMessageBody": "Welcome to the M365PAL SharePoint site! Click the link below and sign in."
  }
}

In HTTP request body, use the dynamic content of the form to populate the fields invitedUserDisplayName & Emailaddress. The invite redirectUri is the output of the compose action which has the SharePoint site url. I have added a delay of one minute before granting access to SharePoint site for the external user, this step is to make sure there is an entry in Azure AD for the external user/guest account.

Custom connector can be used for calling the Graph API for sending invitations instead of using HTTP connector, you can refer to the post Call Microsoft Graph API in Power Apps and Power Automate using a Custom connector for detailed instructions.

Grant Access to SharePoint site for the external user:

As soon as the guest account invite is sent from the above Microsoft graph API request HTTP action, it is time to grant access to the SharePoint site for the external user. There is a SharePoint REST API endpoint to add a user to a SharePoint group (Owners, Member, Visitors), find below the request details

Request URL: https://tenantname.sharepoint.com/sites/siteName/ _api/web/sitegroups/GetById(groupId)/users

For the groupId to the corresponding SharePoint group, refer to the following table

SharePoint GroupGroupId
Owners3
Members5
Visitors4

Headers:

Key: accept value: application/json;odata.metadata=none

Key: content-type value: application/json

Body:

{'LoginName':'i:0#.f|membership|userPrinipalNameorEmailaddressofExternalUser'}

For the external user, the email address used to send the invite works.

Go back to the flow and add the action Send an HTTP request to SharePoint to call the above REST api. Find below the screenshot of the action

The above action uses delegated permission, the user of the connection should have access to the SharePoint site. As of now, there is no Graph API for adding the user to a SharePoint group but you can register an app in Active directory and add permission for SharePoint to call the above REST API. Refer to the documentation Granting access via Azure AD App-Only for calling the REST API using the registered AD app.

Testing the flow:

The whole flow can now be tested by submitting the form which sends the adaptive card on Teams first as shown below

After the card is approved, the invite is sent to the external user. After the external user accepts the invite, the user should be automatically redirected to the SharePoint site with the appropriate access. The access to the SharePoint site for the external user can be validated by the checking the membership of the SharePoint group in the site even before the user accepts the invitation. The site members can also be validated by accessing the URL for All users list:

https://tenantName.sharepoint.com/sites/siteName/_layouts/15/people.aspx?MembershipGroupId=0

This approach of granting access to SharePoint site for external user can be applied to internal users by turning off the access requests.

Limit External Sharing by domain:

The external sharing on SharePoint can be restricted based on domain of the external user. To enable the setting login into the SharePoint admin center > Policies > Sharing > Enable the checkbox Limit external sharing by domain > Add domain

Onboard External users to a Microsoft Team:

To onboard the external user to a Microsoft Team, the only change to the above flow is, instead of adding the user to the SharePoint group the user must be added as a Member to the Microsoft 365 group connected to the Microsoft Teams. The graph API to add a member to a Microsoft Team is

Request Type: POST

Request URL: https://graph.microsoft.com/v1.0/teams/{team-id}/members

The team-id is the Microsoft 365 group object Id, as there is always a Microsoft 365 group connected to a Microsoft Team.

Body:

{
    "@odata.type": "#microsoft.graph.aadUserConversationMember",
    "roles": ["owner"],
    "user@odata.bind": "https://graph.microsoft.com/v1.0/users(userObjectIdofGuest')"
}

The expression to get the user object Id of the external user as per the below screenshot is

outputs(‘HTTP-SendGuestInvitation’).body.invitedUser.Id The expression can be used in a compose action to get the Object Id of the external user which can be used in the Graph API request to add the member to a Team. HTTP-SendGuestInvitation is the name of the HTTP Action.

Permission for the Azure AD App to add a member to a Microsoft Team:

The application permission Group.ReadWrite.All has to be added on the Azure AD app, if you are going to be using the same JSON webtoken generated above. There is delegated permission as well for adding members.

https://graph.microsoft.com/Group.ReadWrite.All

I recommend you read the following documentation from Microsoft for External sharing

https://docs.microsoft.com/en-us/microsoftteams/manage-external-access

https://docs.microsoft.com/en-us/microsoftteams/guest-access

https://docs.microsoft.com/en-us/microsoftteams/communicate-with-users-from-other-organizations

https://docs.microsoft.com/en-us/microsoft-365/community/managing-external-guest-in-sharepoint-vs-teams

Summary: With this, the Power Automate flow should send the invitation as shown below to the external user.

If it is for a Microsoft Team, the external user should be licensed for teams service to open it on their teams client. The same flow can be also configured for Microsoft 365 group. If you are visiting my blog for the first time, please do look at my other blogposts.

Advertisement

How to use Microsoft graph SharePoint Sites.Selected application permission in a Azure AD application for more granular control

As per this announcement made on Feb 2021, Microsoft graph now provides option to have granular permissions level using Sites.Selected application permission for the AD application instead of granting permission for all the sites in the tenant. The permission Sites.Selected does not provide access to any SharePoint site collections for the application unless the AD application has been assigned with permission roles read or write by an Admin. On this post let us see how to grant a site permission (Read or Write) to an AD Application with Sites.Selected permission by using postman client. As of the time I am writing this post there is no user interface to assign permissions to specific site collections for the application.

Pre-Requisite:

  1. Register Azure AD Application (APP 1) in Azure AD Portal with the following permissions
    • Sites.Selected (Admin Consented)
  2. Another AD Application (APP 2) with following permission only for the admins to assign selected roles to the above App
    • Sites.FullControl.All (Admin Consented)

App Registration:

Start with registering the above said two Azure AD applications

APP 1:

Register an Azure AD application with the following permission

APP 2 (Admin App):

Another app for admins for granting roles to APP 1

Grant permission role to the SharePoint site for the Azure AD Application:

This step is grant permission for the Azure AD application with Sites.Selected application permission to a given site collection. Perform the following steps to grant the role (Read/Write or Read and Write) to the AD app (APP 1)

  1. Gather the Client ID, Tenant ID and Client secret of the admin app
  2. In PostMan, make a HTTP request to generate the access token for the admin app – APP 2

Request Method: POST

Request URL: https://login.microsoftonline.com/yourtenantID/oauth2/v2.0/token

Request Header:

Key: Content-Type

Value: application/x-www-form-urlencoded

Request Body:

grant_type: client_credentials

scope: https://graph.microsoft.com/.default

client_id: adminappclientid

client_secret: adminappclientsecret

  1. Copy the access_token to be used for granting roles.
  2. Get the Client ID of the Azure AD Application – APP 1 with Sites.Selected permission
  3. Decide on the Role (Read or Write) for the granting the Site specific role for the APP 1 with Sites.Selected permission.
  4. Get the SiteId of the SharePoint site to be assigned permissions for the application (App 1). An easy way to get the siteId is by viewing the page source from the browser with the site open.
  5. In PostMan, make a HTTP request to grant the site role to the APP 1. Replace the siteId with the actual siteId which will be a guid

Request Method: POST

Request URL: https://graph.microsoft.com/v1.0/sites/siteId/permissions

Request Header:

Key: Content-Type

Value: application/json

Request Body: raw

Replace the id with APP 1 client id and the display name of the APP 1

{

  "roles": ["write"],

  "grantedToIdentities": [{

    "application": {

      "id": "xxxxxx-APP1GUID-4ad9-xxxx-4d36e68b0454",

      "displayName": "AppNamewithSelectedPermissions-App1"

    }

  }]

}
  1. Paste the access token on the token box as shown below with Authorization type selected as Bearer Token
  1. Send the request for granting the role for APP 1. After the request is made the APP 1 with the Sites.Selected permission has access to the site with write role we have granted to. The same way you can assign app access to multiple SharePoint sites.

Grant the Role using PnP PowerShell:

There is a PnP PowerShell cmdlet to grant access to SharePoint site for the registered AD application with Sites.Selected permission. The command to grant permission can be executed by the Site Collection administrator after creating a connection to the site

Connect-PnPOnline https://tenantname.sharepoint.com/sites/siteName -Interactive

You will be prompted to enter credentials including the second factor. After the connection is created, enter the following command to grant Write permission to the AD App

Grant-PnPAzureADAppSitePermission -AppId 'AzureAppIdwithSitesdotselectedpermission' -DisplayName 'App Name here' -Site 'https://tenantname.sharepoint.com/sites/sitename' -Permissions Write

To install PnP PowerShell module on the local workstation, enter the following command

Install-Module -Name PnP.PowerShell

There is also a PnP cmdlet to register an AD app in the Azure Active directory.

Grant the Role by an Admin using the Graph Explorer tool:

Role can also be assigned by an admin with out having the admin AD app (APP 2) using the graph explorer tool. This can be done only by an Admin

If there is any error related to permissions, make sure the admin consents to Sites.FullControl.All for the Graph tool. There is also an SPFx community webpart developed by a community member with User Interface for this operation

https://github.com/pnp/sp-dev-fx-webparts/tree/master/samples/react-sites-selected-admin

Reference:

Assign permission role programmatically: https://docs.microsoft.com/en-us/graph/api/site-post-permissions?view=graph-rest-1.0&tabs=csharp

Summary:

On this post we have seen how to grant access to Azure AD which has the Sites.Selected permission. You can also grant permission/role to an app with sites.selected permission programmatically. If you are using SharePoint API instead of Graph API in the Azure AD app registration, Sites.Selected is available on Application Permission as shown below

Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

How to create & setup Dynamic Microsoft 365 Group or Distribution list based on the user’s domain for Teams, Yammer and Exchange

There are many organizations maintaining multiple domains on a single Microsoft 365 or Azure AD tenant, in those cases there might be a need to create dynamic Microsoft 365 groups, security groups & distributions list based on the user’s domain to manage the group’s membership. On this blogpost, let us see how to

  1. Create Dynamic Microsoft 365 group based on the user’s domain for Teams & Yammer
  2. Create a Dynamic distribution list based on user’s domain in Exchange online

To begin with let us see some basics of a Dynamic group. The membership of a dynamic group will automatically update as people join, leave, or move within the organization whenever the user’s Azure Active Directory attributes are changed. In simple terms, rules determines the group membership. The users will be added or removed automatically as and when the user attributes change or users join and leave the tenant which reduces the administrative effort of adding and removing users from a group. Dynamic group can be created based on variety of attributes including role, location, department etc.

Create Dynamic Microsoft 365 group based on the user’s domain for Teams & Yammer

Microsoft Teams and Yammer (Microsoft 365 Connected) supports dynamic membership. It enables the membership of Team or Yammer to be defined by one or more rules that check for certain attributes in Azure AD. Microsoft Teams & Yammer creates a Microsoft 365 group in Azure AD. For this post, the membership rule will be simple one which is based on the user’s domain and country. You can also have a complex rule involving multiple Azure AD attributes like Title, Geography, Department etc. Before we proceed further, there are some pre-requisite & facts to be considered before creating a dynamic group.

  • User Administrator or Global administrator role in Azure AD
  • Users you foresee to be part of a dynamic group membership rule should have an Azure AD premium License P1 or P2
    • Microsoft 365 E3, E5, Front line workers MF3 & MF1 has Azure AD premium 1 service which should suffice.
  • An Azure AD organization can have maximum of 5000 dynamic groups.
  • Any number of Azure AD resources can be members of a single group.

Dynamic Membership based on Domain for Teams:

To create a Dynamic membership MS team, create a Microsoft 365 group first with Dynamic membership in Azure Active directory. You can create a dynamic group from PowerShell but here I will be using Azure Ad GUI to create the dynamic Microsoft 365 group with rule to add users based on their domain and country. I have added a domain m365pal.me to my Azure AD tenant which I will be using here for this example.

  1. Sign in to Azure AD Admin center with administrator role in the Azure AD organization
  2. Click Groups and then click + New Group
  3. Select the Group type as Microsoft 365. Dynamic membership will also work with Security group but for team it should be Microsoft 365 group.
  4. Enter the Group Name & Group email address
  5. Select the Membership type as Dynamic User
  6. Select the Owner and then
  7. Under Dynamic user members section, click Add dynamic query
  8. In Dynamic membership rules panel, add rule to define membership based on users domain & country
    • First rule for Domain: under Property column select userPrinicipalName, Operator should be Contains and the Value should be the domain name in format “@yourdomain.com”. This rule will add all users with the UPN user@yourdomain.com. Now click + Add expression to add the second rule
    • Second rule for country: under Property column select country, Operator should be  Equals and the value should be the country name.
  1. You can also validate the rules by clicking the link Validate Rules and then by adding users to check if the user satisfies the rule
  2. Click Save. This is how it should look like
  1. Click Create.
  2. After waiting for couple of minutes, check the group membership. Please find below screenshot for the group which has two members satisfying the condition. You can also notice the + Add members link is disabled since the group is dynamic membership and not assigned. To modify the rules, click the link Dynamic membership rules link.
  1. Now we are ready to create the MS Teams, go to https://teams.microsoft.com/ and then click Join or create a team at the left bottom corner and then Click Create a team
  2. Click From a group or team and then click Microsoft 365 group
  3. Now select the group you have created in Azure AD and then click Create.
  1. The team is now created, you can find the team on the list. Check the membership of the team which will have the two users satisfying the rules and the owner of the group. One more thing to notice here is the message which says The membership settings prevents you from adding or removing members.
  1. Voila! Dynamic Microsoft team is now created & setup.

If you have an existing team to be converted to a Dynamic team, find the Microsoft 365 group in Azure AD for the Team you wish to convert and then update the membership status from Assigned to Dynamic user with membership rules

Dynamic Membership based on Domain for Yammer:

Yammer (Microsoft 365 Connected) also supports dynamic membership. Find the steps below to create a dynamic yammer group based on the user’s domain. Find the steps below

  1. Sign in to https://yammer.com/ with your organizational ID
  2. Click Create a Community and then Enter the name of the Community
  3. Click the button Create
  1. Now sign in to Azure AD Admin center to the update the membership settings of the Microsoft 365 group connected to the Yammer community. Find the yammer group and then click
  1. Click Properties under the Manage blade and then change the membership type from Assigned to Dynamic user
  1. After updating the membership type to Dynamic user. You will now have option to enter the dynamic query. Click dynamic query
  1. In Dynamic membership rules panel, add rule to define membership based on users domain
    • Rule for Domain: under Property column select userPrinicipalName, Operator should be Contains and the Value should be the domain name in format “@yourdomain.com”. This rule will add all users with the UPN user@yourdomain.com. Now click + Add expression to add rules based on need
    • Click Save
  1. Click Save. Wait for couple of minutes for the membership to be updated.
  2. Now check the Yammer group in Yammer.com for the membership status. Please find below screenshot for your reference which will not have the + icon on the highlighted members section for adding users since this is now a dynamic yammer group

Also, Microsoft 365 group/Security group can be used for different use cases. See some sample use cases below

  • You can use to target SharePoint page/news to specific audience with the help of Microsoft 365 group or Security group. Will it not be more powerful if you use dynamic groups within a SharePoint to target content certain group of audience!
  • Assign Microsoft Licenses to users based on Dynamic Group.
  • Grant access to an App (PowerApps etc) using the dynamic group targeting certain departments, geographies etc

Reference:

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/groups-create-rule

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/groups-dynamic-membership

https://docs.microsoft.com/en-us/microsoftteams/dynamic-memberships

https://docs.microsoft.com/en-us/yammer/manage-yammer-groups/create-a-dynamic-group

https://docs.microsoft.com/en-us/yammer/manage-yammer-groups/yammer-and-office-365-groups

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/directory-service-limits-restrictions

Create a Dynamic distribution list based on user’s domain in Exchange online:

Dynamic distribution groups are mail-enabled Active Directory group to distribute email messages to all its members within a Microsoft Exchange organization. Unlike regular distribution lists that contain a defined set of members, the membership list for dynamic distribution groups is calculated each time a message is sent to the group, based on the filters and conditions that you define in the group. You can create a Dynamic Distribution list from Exchange Admin center as shown below but the options to write advanced filter conditions or rules are limited so PowerShell is preferred.

Dynamic Distribution list from PowerShell:

Make sure the Exchange online PowerShell module is installed. There are some limitations to create a recipient filter (Rules) that worked based on user’s domain with the operator like or contains but there is a workaround. The filter works based on the exchange property WindowsEmailAddress which is always the primary SMTP address, you can also consider using the property WindowsLiveID. Follow the steps below to create a Dynamic Distribution list based on user’s domain

  1. Load the module by the running the command Import-Module ExchangeOnlineManagement
  2. Connect to the Exchange online PowerShell in Microsoft 365
Connect-ExchangeOnline -UserPrincipalName userId@domain.com -ShowProgress $true
  1. After authentication, enter the following command to create the Dynamic DL based on User’s domain. I have added the RecipientTypeDetails in the RecipientFilter to apply the filter rule only to user mailboxes which excludes the SharedMailboxes
New-DynamicDistributionGroup -Name "All Users - M365PAL DL" -RecipientFilter "(RecipientTypeDetails -eq 'UserMailbox') -and (WindowsEmailAddress -eq '*@yourdomain.com')"
  1. You can also validate the users using the following script
Get-Recipient -RecipientPreviewFilter (Get-DynamicDistributionGroup "All Users - M365PAL DL").RecipientFilter
  1. To view the attributes to be used in the recipient filter enter the following command
Get-User -Identity user@yourdomain.com | Format-List

Reference:

https://docs.microsoft.com/en-us/exchange/recipients/dynamic-distribution-groups/dynamic-distribution-groups

https://docs.microsoft.com/en-us/powershell/module/exchange/get-user

https://docs.microsoft.com/en-us/exchange/recipients/dynamic-distribution-groups/view-dynamic-distribution-group-members

Summary: On this post we have seen how to create dynamic groups based on user’s domain. Do some planning to start using the dynamic groups which will help reduce lot of administrative overhead. Hope you have found this informational & helpful. Let me know any feedback or comments on the comment section below

How to use your MS Teams as an email distribution list

When you create a Microsoft Team, a Microsoft 365 group is created to manage the team membership like Owners, members, guests. I would rather say the Microsoft 365 group is a backbone of a Team. Through the group you also get an email address for the MS team. Find the other Microsoft 365 services which gets created per this documentation whenever there is a Team provisioned

On this blogpost let us see how to enable a team which can also act as an email distribution list so that you can send an email to all the team members, by default this option is disabled. You will have to be an Owner of the team to set this up. There are couple of ways to do this

  • Graph Explorer
  • Outlook
  • Exchange Online Powershell
  • Exchange Online Administrator

Graph Explorer:

Graph explorer is a utility that will let you make requests and get responses against the different graph endpoints as a signed in user (Delegated User). To enable the email distribution functionality, we will have to get the group id of the team for setting a value to True for the property autoSubscribeNewMembers. To get the Group Id information go to the Team and click the Get link to team as shown below

Copy the content from the popup which should be in the below format

To get the group details like Email Address, Mail Nick Name, Display Name etc make a GET request to the following endpoint from the explorer

https://graph.microsoft.com/v1.0/groups/groupId

Make a PATCH request to the endpoint https://graph.microsoft.com/v1.0/groups/groupId with the payload

{
“autoSubscribeNewMembers”:true
}

Now make a GET request on the following endpoint with the group id of the team https://graph.microsoft.com/v1.0/groups/groupId?$select=autoSubscribeNewMembers

to get its status. It is all set now.

Outlook:

The Microsoft 365 group inbox for a Team is not available in Outlook but it can be accessed through the SharePoint site associated to the group. Open the SharePoint site from any of the Teams channel as shown below

Click Conversations on the left navigation

The URL of the Outlook will be in following format: https://outlook.office365.com/mail/group/domain/mailNickName/email

Access the settings of the group

Click Edit group from the Group Settings

On the Group Settings popup, enable the Subscription as shown below and then Save it. By default this setting is disabled for the Microsoft 365 group.

Exchange Online PowerShell:

The same setting can also be enabled from Exchange online PowerShell if you have Exchange online Administrator access on the tenant. Make sure the Exchange online PowerShell module is installed. Follow the steps below to turn on AutoSubscribeNewMembers which distributes emails to all users

  1. Load the module by the running the command Import-Module ExchangeOnlineManagement
  2. Connect to the Exchange online PowerShell in Microsoft 365
    1. Connect-ExchangeOnline -UserPrincipalName userId@domain.com -ShowProgress $true
  3. Set-UnifiedGroup -Identity 539818c4-XXXX-XXXX-b781-78dff1762b72 -AutoSubscribeNewMembers or Set-UnifiedGroup -Identity “Team Display Name” -AutoSubscribeNewMembers
  4. To disable the setting: Set-UnifiedGroup -Identity ” Team Display Name ” -AutoSubscribeNewMembers:$false

Refer to the documentation from Microsoft for more Exchange online commands related to the Microsoft 365 group.

Exchange Online Administrator

Login into the Exchange Online Admin center and click on Groups from the dashboard section. Execute the below steps

  1. Find the group associated to the team (Team Display Name) from the list and then select
  2. Click on Edit (Pencil Icon) from the ribbon
  3. On the General tab, Enable the property Subscribe new members and then Save

Summary: The same setting can also be applied to a Team created through a Microsoft 365 group. Hope you have found this informational. There were already lot of blogs talking about groups

Reference:

https://support.microsoft.com/en-us/office/learn-about-microsoft-365-groups-b565caa1-5c40-40ef-9915-60fdb2d97fa2

https://support.microsoft.com/en-us/office/follow-a-group-in-outlook-e147fc19-f548-4cd2-834f-80c6235b7c36#ID0EAACAAA=Web

https://sharegate.com/blog/office-365-groups-explained

https://www.jumpto365.com/blog/everyday-guide-to-office-365-groups

How to setup custom domain and email address in Microsoft 365 online tenant

On this blogpost let us see how to add a custom domain and configure exchange email address for the added domain in a Microsoft 365 tenant. This will allow you to create M365 identities for the users in the Microsoft 365 tenant like user@domain.com instead of user@domain.onmicrosoft.com. This setup is also required if you have a Hybrid setup with users from Onpremise Active directory. Azure AD connect tool helps you synchronize your AD identity from Onpremise to Azure AD or Microsoft 365 tenant directory only if there is a custom domain added to the directory. The custom domain can be added from Microsoft 365 tenant admin center or Azure Active directory portal associated to the M365 tenant.  

Pre-Requisites:

  • Own a Domain from any domain providers
  • Global administrator of Microsoft 365 tenant

If you don’t add a domain, user account in your organization will use the default onmicrosoft.com domain for their email address and UPN. To setup and configure a custom domain, you will have to

  1. Add a TXT or MX record
  2. Add DNS records to connect Microsoft 365 services

For this blog post I have used Domain.com provider to add the DNS records for the custom domain

Add a TXT or MX record:

The first step is to prove you are Owner of the domain and also make the domain is not associated to different tenant. To generate the DNS record values and to add the custom domain login to the Microsoft 365 Admin Center

  1. Select Show all > Settings > Domains
  2. Click Add domain
  3. Enter the custom domain name you own
  4. Click on the button Use this domain

Select Add a TXT record to the domain’s DNS records but you can also add a MX record or add a text file to the domain’s website. Find the different options

  1. The DNS record values for the TXT record will be generated as shown below. TTL 3600 seconds is 1 hour
  1. Add the DNS record for TXT from the domain provider interface for managing the records
  1. Go back to the Admin center and then click Verify. It takes around 15 mins to an hour for the DNS records to propagate, sometimes it may even take more time. Keep trying till the domain in verified. Once the domain is verified you will be able to proceed to the next step for configuring the Microsoft 365 services like exchange etc. You can also Skip and do the configuration later but with this setup you can create user accounts by using the custom domain as its UPN e.x user@domain.com without email address. Find instructions on this link to add a custom domain from Azure Active directory portal.

Add DNS records to connect Microsoft 365 services:

The domain is added & verified, now its time to connect the Microsoft services like Email (Exchange Online, Outlook), Mobile device Management aka MDM with the custom domain. On this post will be connecting only to Exchange online to receive email through Microsoft 365. After this setup is done Exchange online will be your new email host for the domain. After the domain is verified from the step above, select Add your own DNS records and click Continue button as shown below

The following DNS records will be generated as shown below

  • MX Records (Mandatory)
    • Sends incoming mail for your domain to the Exchange Online service in Office 365. Mails are delivered to the mail exchange server with the lowest preference number for this record, typically.
  • CNAME Records (Optional: For Outlook client to work)
    • Helps Outlook clients to easily connect to the Exchange Online service by using the Autodiscover service. Autodiscover automatically finds the correct Exchange Server host and configures Outlook for users
  • TXT Records (Optional: SPF record for prevention of spamming)
    • Helps to prevent other people from using your domain to send spam or other malicious email. Sender policy framework (SPF) records work by identifying the servers that are authorized to send email from your domain

Go back to the domain hosting provider interface to add the above DNS records, to get the values for each record expand each record shown on the above interface.

MX Record:

Set the priority to the Highest or to the number 0 and then add the DNS record. If the domain is xyz.com

Sample value/Content: xyz-com.mail.protection.outlook.com

CNAME Records:

Name: Autodiscover

Value/content: autodiscover.outlook.com

TTL: 1 hour

TXT Records (SPF):

There can be only one SPF record on the DNS records so if there are another record already (default), refer this link for more information. I already had the default one so the valye for the TXT record looked like v=spf1 ip5:XX.XX.XXX.X/XX include:spf.protection.outlook.com -all

ipX:XX.XX.XXX.X/XX is the default one

Now after all the DNS records are added, choose Continue. This will take you to the last page of the wizard with the message Domain setup is complete

Now the setup is completed, you can create users using the new custom domain or change an existing users UPN and email address on Admin center with the following steps

  1. Go to Users > Active users page
  2. Select the user’s name, and then on the Account tab select Manage username.
  3. On the Aliases box, enter the new alias@yourdomain.com and then click Add
  4. Select the new alias and if required change it to the primary email.

Summary: On this post we have seen how to configure a custom domain with email. There can also be multiple domains in one tenant. Hope you have found this informational. Let me know any feedback or comments on the comment section below

Reference:

https://docs.microsoft.com/en-us/microsoft-365/admin/get-help-with-domains/create-dns-records-at-any-dns-hosting-provider

https://support.microsoft.com/en-us/office/connect-your-domain-to-office-365-cd74b4fa-6d34-4669-9937-ed178ac84515

https://docs.microsoft.com/en-us/microsoft-365/admin/setup/add-domain

https://support.microsoft.com/en-us/office/add-a-new-domain-in-microsoft-office-365-285437c3-d6c9-45cd-8b48-ed29c670c796

https://docs.microsoft.com/en-us/microsoft-365/admin/setup/domains-faq?view=o365-worldwide

https://docs.microsoft.com/en-us/microsoft-365/enterprise/external-domain-name-system-records

https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/set-up-spf-in-office-365-to-help-prevent-spoofing?view=o365-worldwide

Tools to call Microsoft Graph API endpoints as a User and application

This blogpost will help you to explore and interact with MS graph API endpoint’s using the following tools

  • Postman client
    • Signed in as a user/On-behalf-of API call (Delegated permission)
    • Application/daemon API call (Application permissions)
  • Graph Explorer

I have used MS graph extensively on different MS cloud services like SharePoint, PowerAutomate, PowerApps, Azure services like Azure functions and on devices like Raspberry Pi. It is a very powerful service in Microsoft 365 platform. Let start with some basics

Introduction:

MS Graph API is a RESTful web API which enables you to access different Microsoft 365 cloud service resources through its unified programmability model.

Microsoft Graph exposes REST APIs and client libraries to access data on the following Microsoft cloud services:

  • Microsoft 365 services: Delve, Excel, Microsoft Bookings, Microsoft Teams, OneDrive, OneNote, Outlook/Exchange, Planner, SharePoint, Workplace Analytics.
  • Enterprise Mobility and Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune.
  • Windows 10 services: activities, devices, notifications, Universal Print (preview).
  • Dynamics 365 Business Central.

Permission Types:

MS Graph exposes granular permissions that controls the access of the apps that has to the different resources like sites, users, groups etc. There are two types of permission

  • Delegated permissions are used by apps that have a signed-in user present. For these apps, either the user or an administrator consents to the permissions that the app requests and the app can act as the signed-in user when making calls to Microsoft Graph.
  • Application permissions are used by apps that run without a signed-in user present. For e.g Apps that run as background services or daemons. Application permissions can only be consented by an administrator.

Access token:

To call a MS Graph API all you need is an access token in the authorization header of an HTTP request.

GET https://graph.microsoft.com/v1.0/me/ HTTP/1.1

Host: graph.microsoft.com

Authorization: Bearer EwAoA8l6BAAU … 7PqHGsykYj7A0XqHCjbKKgWSkcAg==

The access tokens are issued by the Microsoft identity platform which contains information to validate if the requestor has appropriate permissions to perform the operation they are requesting. An active directory app is a pre-requisite to generate an access token to call a Graph API endpoint.

There are also Microsoft identity platform authentication libraries for .NET, JS Android, Objective-C, Python, Java, Angular facilitating validation, cookie handling, token caching and on maintaining a secure connection. Let’s now go ahead and see the tools

MS Graph Explorer:

Graph explorer is a web-based tool which can be used to build and test requests using Microsoft Graph API. The explorer can be accessed from the following URL:

https://developer.microsoft.com/en-us/graph/graph-explorer

There will be a default Active directory application on the Organizational Active directory of the M365 tenant by the name Graph Explorer with application id de8bc8b5-d9f9-48b1-a8ad-b748da725064. This app can be accessed from the Enterprise applications blade of the Active directory as shown below

Delegated permissions are used by Graph Explorer. Based on your access role & admin consent’s you would be able to call different Microsoft Graph API from this tool. After you have signed into the Graph Explorer tool, the access token will be generated automatically

To view the token information, copy the token and paste it on the utility https://jwt.ms/

If your token has a scp (Scope) claim, then it’s a user based token (Delegated permissions). It is a JSON string containing a space separated list of scope the use has access to call different graph endpoints. You can also find other information related to the issued token, token issued at (iat), expirty not before (nbf), expiry time (exp). The data is in UNIX time stamp but you can convert this information to standard time using the online URL

https://www.epochconverter.com/

More information about JWT can be found at

https://auth0.com/docs/tokens/json-web-tokens

Postman Client:

Postman is a tool that can be used to build and test requests using the Microsoft graph API’s. To use this tool for testing the Graph API endpoint’s, register an app in Azure Active directory as per the instructions from this blog post. Provide the permission (Delegated & Application) as per your need to test it using Postman.

Copy the client id, client secret & tenant ID of the registered app. To access the various endpoints like authorization and token, click on the Endpoints from the Overview section of the Active directory app.

Setting up the environment using Postman collections:

There are Postman collections with many MS graph API requests created by Microsoft for us to explore. Import the collections and setup the environment (Client ID, Client secret, tenant id) for Application API calls and on-behalf-of API calls as per the instruction from the following article

https://docs.microsoft.com/en-us/graph/use-postman

Application API Token:

To generate an application token, make a POST request to Get App-Only Access Token from the collection Microsoft Graph. The grant_type is client_credentials since it is Application permissions.

Token Validity:

The token is valid for 3599 seconds which is 1 hour. Post that the token will expire, you will have to regenerate the token by making another call.

The AccessToken (Application API call) will be generated and automatically stored on the Environment (Microsoft Graph environment) AppAccessToken with the help of a script on the Tests tab in Postman. Copy the access token value & paste it on the utility https://jwt.ms/. Find the decoded token below which has information like the Application ID/client id of the AD app, display name and roles to which the app has access to poll the graph endpoint.

Graph API call:

The call to the Graph should have the bearer token

Signed-in user/on-behalf-of API Token:

To generate a Signed-in user token, make a POST request to Get user Access Token from the collection Microsoft Graph. The grant_type is password since it is delegated permissions.

The AccessToken (Signed-in user API call) will be generated and automatically stored on the Environment (Microsoft Graph environment) UserAccessToken with the help of a script on the Tests tab in Postman.

Copy the access token value & paste it on the utility https://jwt.ms/. Find the decoded token below which has information like the Application ID/client id of the AD app, display name and scopes (scp) to which the app has access to poll the graph endpoint. If you remember the Application API token had roles & not scopes, so this is how you can identify the token type.

Storing the production User ID and password is not recommended on the Environmental variables since the information is stored in Postman but this can be handled by generating an access token from the request Authorization tab, set the type as OAuth 2.0 and click Get New Access Token button

Fill in all the information gathered from the App in Azure AD like Appid, Secret, Endpoints (Authorization and Token), state can be any random value

Click Request token, this will prompt the user to enter the Username and password. After authentication, it will generate the token which could be used further to make API calls.

Graph API call:

The call to the Graph should have the bearer token on the Authorization tab or on the Headers tab

Summary: On this post we have seen how to use tools like Graph explorer & Postman to test different MS graph API endpoints. You can make requests like GET, POST, PUT, PATCH, DELETE based on its availability. Refer to the Microsoft documentation for v1.0 and beta endpoints. Once you have explored & tested the API, you are ready to use on applications using the available SDK’s for different programming languages. Let me know any feedback or comments on the comment section below

Multiple ways to access your On-premise data in Microsoft 365 and Azure

If your organization is using a hybrid cloud environment, this post will shed some light to integrate on-premise resources with Microsoft 365 & Azure services. Hybrid integration platforms allows enterprises to better integrate services and applications in hybrid environments (on-premise and cloud). In this blog post, I will write about the different services & tools available with in Microsoft Cloud which allows you to connect or expose your On-premises data or application in Office 365. There are still many enterprise organizations on Hybrid mode due to various factors. It can be a challenging task to integrate your on-premises network but with right tools & services in Office 365 & Azure it can be easier. Find below the high-level overview & some references on how to

  1. Access your on-premise data in Power Platform & Azure Apps (Logic Apps, Analysis Services & Azure Data factory)
  2. Programmatically access your on-premise resources in your Azure Function app
  3. Access on-premise resources in Azure automation account
  4. Expose your on-premise Application or an existing WEB API in Office 365 cloud

Access on-premise data in Power Platform & Azure Apps (Logic Apps, Analysis Services & Azure Data factory):

The on-premises data gateway allows you to connect to your on-premises data (data that isn’t in the cloud) with several Microsoft cloud services like Power BI, Power Apps, Power Automate, Azure Analysis Services, and Azure Logic Apps. A single gateway can be used to connect multiple on premise applications with different Office 365 applications at the same time.

At the time of writing, with a gateway you can connect to the following on-premises data over these connections:

  • SharePoint
  • SQL Server
  • Oracle
  • Informix
  • Filesystem
  • DB2

To install a gateway, follow the steps outlined in MS documentation Install an on-premises data gateway. Install the gateway in standard mode because the on-premises data gateway (personal mode) is available only for Power BI.

Once the data gateway is installed & configured its ready to be used in the Power platform applications.

  1. PowerApps
  2. PowerAutomate
  3. PowerBI

The other catch the gateway is not available for the users with Power Automate/Apps use rights within Office 365 licenses as per the Licensing overview documentation for the Power Platform. Data gateways can be managed from the Power Platform Admin center.

Shane Young has recorded some excellent videos on this topic for PowerApps & PowerBI.

To use in

  1. Azure Logic Apps
  2. Azure Analysis service
  3. Azure Data Factory

create a Data Gateway resource in Azure.

High Availability data gateway setup:

You can use data gateway clusters (multiple gateway installations) using the standard mode of installation to setup a high availability environment, to avoid single points of failure and to load balance traffic across gateways in the group.

No need to worry about the security of the date since all the data which travels through the gateway is encrypted.

Data gateway architecture:

Find below the architecture diagram from Microsoft on how the gateway works

I recommend you to go through On-premises data gateway FAQ.

Integration Service Environment:

As per the definition from Microsoft an integration service environment is a fully isolated and dedicated environment for all enterprise-scale integration needs. When you create a new integration service environment, it’s injected into your Azure Virtual Network allowing you to deploy Logic Apps as a service in your VNET. The private instance uses dedicated resources such as storage and runs separately from the public global Logic Apps service. Once this logic apps instance is deployed on to your Azure VNET, you can access your On-premise data resources in the private instance of your Logic Apps using

  • HTTP action
  • ISE-labeled connector for that system
  • Custom connector

For the pricing of ISE, refer this link.

Programmatically access your on-premise resources in your Azure Function app

As you all know Azure Functions helps in building functions in the cloud using serverless architecture with the consumption-based plan. This model lets the developer focus on the functionality rather than on infrastructure provisioning and maintenance. Okay let’s not more talk about what a Function app can do but let us see on how to connect to your on-premise resources (SQL, Biztalk etc) within your function.

During the creation of a Function app in Azure, you can choose the hosting plan type to be

  • Consumption (Serverless)
  • Premium
  • App Service plan

Consumption based plan is not supported for the on-premise integration so while creating the app the hosting plan has to either premium or app service based plan & the Operating system has to to be Windows. On-premise resources can be accessed using

  1. Hybrid Connections
  2. VNet Integration

Hybrid Connections:

Hybrid Connections can be used to access application resources in private networks which can be on-premise. Once the Function app resource is created in Azure, go to Networking section of the App service to setup & configure. Go through the documentation from Microsoft for the detailed instructions to set this up.

How it works:

The Azure Hybrid Connection represents a connection between Azure App Service and TCP endpoint (host and port) of an on-premise system. On the diagram below Azure Service Bus Relay receives two encrypted outbound connections. One from the side of Azure App Service (Web App in our case) and another from the Hybrid Connection Manager (HCM). HCM is a program that must be installed on your on-premise system. It takes care of the integrations between the on-premise service (SQL in this case) with Azure Service Bus Relay.

Once the setup is done, you can create a connection string in Appsettings.json file or from Azure function app interface of your function app. After this you can access the data in your function app code.

I’ve found a couple of interesting blogs about this setup.

VNet Integration:

In the Networking features of the App service, you can add an existing VNET. An Azure Virtual Network (VNet) is a representation of your own network (private) in the cloud. It is a logical isolation of the Azure cloud dedicated to your subscription.

In Azure Vnet you can connect an on-premise network to a Microsoft VNet, this has been documented from Microsoft here. Once there is integration between your Azure Vnet & on-premise network and the VNet is setup on your function app you are set to access on-premise resources in your function app.

Access on-premise resources in Azure automation account:

Azure Automation is a service in Azure that allows you to automate your Azure management tasks and to orchestrate actions across external systems from right within Azure. Hybrid runbook worker feature allows you to access on-premise resources easily. The following diagram from Microsoft explains on how this feature works

I’ve written a blogpost recently about this feature for automating on-premise active directory.

Expose your on-premise Application or an existing WEB API in Office 365 cloud:

Azure Active Directory’s Application Proxy provides secure remote access to on-premises web applications (SharePoint, intranet website etc). Besides secure remote access, you have the option of configuring single sign-on. It allows the users to access on-premise applications the same way they access M365 applications like SharePoint Online, PowerApp, Outlook etc. To use Azure AD Application Proxy, you must have an Azure AD Premium P1 or P2 license.

How it works:

The following diagram from Microsoft documentation shows how Azure AD and Application Proxy works

Find below documentations on how to

  1. Add an on-premises application for remote access through Application Proxy in Azure Active Directory
  2. Secure access to on-premises APIs with Azure AD Application Proxy
  3. Use Azure AD Application Proxy to publish on-premises apps for remote users
  4. Deploy Azure AD Application Proxy for secure access to internal applications in an Azure AD Domain Services managed domain

Once the connector service is installed from your Azure AD application proxy, you can add an on-premise app as shown below

The above step will register an application with App registrations.

Summary: I’ve given some overview about the different services & tools to connect & integrate on-premise resources with Microsoft cloud. Hope you like this post & find it useful. Let me know any feedback or comments on the comment section below

Automate the provision of On-Premise AD Account – Part 2

This post is in continuation to my previous post Automate the provision of Azure AD Account & License assignment – Part 1 for creating account in Azure active directory using Power Automate. On this post I will highlight the feature available in Azure Automation account which can be leveraged to create an On-premise AD account. Refer to this post for the usage of Azure automation account to interact with SharePoint online in Microsoft 365 using Power Automate.

Azure Automation is so easy to setup for automating tasks that interacts with

  • Azure (Azure AD, SQL etc)
  • M365 services (SharePoint etc). 

Automation runbooks in Azure might not have access to resources in other clouds or in your on-premises environment because they run on the Azure cloud platform. To access local resources like On-premise Active Directory which lives behind the firewall, there is a feature within Azure Automation called as Hybrid runbook worker. Azure Automation Hybrid Workers extends Azure Automation into your private networks and allows running runbooks that interacts with resources such as on-premises Active Directory, SharePoint etc.

Hybrid Runbook Worker feature to run runbooks directly on the

  • Computer in On-premise network
  • Any secured network like a virtual machine in Azure behind the firewall
  • Cloud services like AWS etc

that’s hosting the role and against resources in the environment to manage local resources. Refer to this documentation about Hybrid runbook worker for more information.

The following image from Microsoft documentation illustrates this functionality:

Pre-requisite:

  1. Azure Subscription to create
    • Automation Account
    • Log Analytics Workspace
  2. Server (Windows or Linux based)
    • Internet access
    • Port: Only TCP 443 required for outbound internet access

The deployment instructions from Microsoft for

I’ve found a really interesting video on Youtube from Travis Robert regarding this topic to set this up on Windows workstation.

Once the Hybrid runbook worker is setup, you can write PowerShell script to create account in On premise Active directory. Find the link to the script to add a user to Active directory in Onpremise. The parameters for the AD account (attributes like name, location, jobtitle, manager etc) to the runbook can be passed from a SharePoint List in Office 365 which could then be triggered using a Flow.

Summary: I was not able to give you a complete walkthrough but I hope had given some pointers to connect on-premise AD. Forgive my ignorance if I have made some mistakes since I don’t have much experience with IT infrastructure. Hope you find this post useful & informational. Let me know if there is any comments or feedback below.

Access Active Directory user profile attributes using Graph API

Using graph API you can access all the Active directory attributes. The me endpoint gives your profile information https://graph.microsoft.com/v1.0/me. To get a specific user’s information the endpoint should be https://graph.microsoft.com/v1.0/users/useremailaddress

For getting any specific AD attribute you can pass the required attribute as a query string https://graph.microsoft.com/v1.0/me?$select=jobTitle,department,displayName

In bigger active directory implementation, there will also be information stored on the Extension attributes, to get the information you will have to pass the name of the attribute “OnPremisesExtensionattributes” as a query string in the format as

 https://graph.microsoft.com/v1.0/me?$select=jobTitle,department,displayName, OnPremisesExtensionattributes

Graph explorer is a nice tool to test the Graph endpoints. Refer the documentation from Microsoft on the different available AD endpoints

Graph Explorer

The beta ME endpoint https://graph.microsoft.com/beta/me gives more information of the user

The User profile service Rest API endpoint in SharePoint http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties does not provide all the active directory information. For e.g Location, OnPremisesextensionAttributes etc information is not available. SharePoint UPS synchronizes the AD data of all users in schedule basis. So the other option is to use the Graph Endpoint if you need those information for your application customization.

Endpoint point to get a specific attribute is

https://siteURL/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl,AccountName

For more information about different endpoint, refer this documentation from Microsoft.

Automate the provision of Azure AD Account & License assignment – Part 1

A decade back I was part of a team to automate the On & Offboarding process of employees for a customer using .NET framework, it had a module to provision user accounts in an on-premise environment. I still remember having used couple of dll’s for Active directory 2003 & exchange 2007 to create AD & Email account. It was not easy but nowadays with the Office 365 in place its so easy to create account & enable different Office 365 services (Exchange, SharePoint, Yammer etc) for a user in Azure Active directory. This example will be applicable for the Organization which does not have On-premise Active directory. Organizations having On-premise active directory, the user account’s will be synchronized from On-premise AD to Azure AD. On this post I am going show you how to

  1. Create Azure AD account & assign license using Power Automate
  2. Assign License using Graph Endpoint

Create Azure AD account & assign license using Power Automate:

There is a Power Automate action Create user under the connector Azure AD which helps us to create account in Azure AD but there is no action as of now to assign individual license to a user but we can overcome this by adding the user to the AD security group which has a license assigned to it.

There is a flow action Add user to group under the same connector for adding the user to the security group, all the members of the group will get the license assigned on that group. The Azure AD connector does not return custom attributes of Azure AD. For e.g you can’t assign a value to a custom AD attribute with the Create user action, if you want to assign a custom attribute or an attribute which is not exposed in the Create User action then the account has to be created using PowerShell. There are ways to call a PowerShell script from Azure Automation Runbooks with the help of a flow action.

Other Azure AD actions apart from the above screenshot which could be of use are

  • Create group
  • Get group members
  • Get groups of a user
  • Get user
  • Remove Member from Group
  • Update user

There are templates available in Power automate template section which helps you create account based on the information from the SharePoint List, based on HTTP request etc

Prerequisite:

  • Permissions on Azure AD:
    • Group.ReadWrite.All
    • User.ReadWrite.All
    • Directory.ReadWrite.All
  • Security group with license assigned

For assigning a license to Security group, go to Azure AD Admin center. Follow this documentation from Microsoft to assign license to a group.

You can also turn off certain services from the license to the group, for e.g Turning off the Power App service for the user

You can also use dynamic groups for assigning license to a user, if you have dynamic group based license assignment to a user then you could ignore the step on the flow to add user to the security group. Dynamic groups works based on rules to determine group membership, for e.g if a user has an AD attribute set for Department. In this case the AD user created with certain department will get automatically added to the group which will in turn assign a license to the user.

Let’s now create the flow, I have used an Instant flow with trigger Manually Trigger a flow. Add the action Create user from the connector Azure AD

Now add the action Add user to group, the Group Id should be for the Security group which has a license assigned to it. The User Id field should be dynamic value Id from the previous action Create user.

To get the group Id, go to Azure AD

Run the flow. Once the flow runs successful the user account will be provisioned on Azure Ad with a license.

Assign License using Graph Endpoint:

There is a beta graph endpoint to assign license to a user. Find the Microsoft documentation for more information

All types of license (E5, E3, PowerApps, Power etc) has a Service Plan id also called as SKU id. Find the list of SKU id’s on this link if your tenant has procured the license for the service

 To get the available service plan or SKU ID, make a GET call to the endpoint https://graph.microsoft.com/v1.0/subscribedSkus & also from the beta endpoint of the user https://graph.microsoft.com/beta/me

Once the sku id are available based on the type of license to be assigned, you will have to make a POST call to

Endpoint URL: https://graph.microsoft.com/beta /users/testuser10@mydevashiq.onmicrosoft.com/assignLicense

Request Body:

{
  "addLicenses": [
        {
            "disabledPlans": [],
            "skuId": "b05e124f-c7cc-45a0-a6aa-8cf78c946968"
        },
        {
            "disabledPlans": [],
            "skuId": "a403ebcc-fae0-4ca2-8c8c-7a907fd6c235"
        }
  ],
  "removeLicenses": []
}

The first SKU id is for Enterprise Mobility & Power BI (Free)

To remove the license for a user, use the collection removeLicenses. This graph endpoint to assign license can also be called from a Flow.

Summary: You can also use a HTTP request trigger in the Flow for integrating with other applications. On next post I will write about creating account in On-premise Active Directory. Hope you find this post useful & informational. Let me know if there is any comments or feedback below.