In this post, we will talk about how to get the access token in CSOM C# and then talk to Graph.
What is the Trick?
The problem is to authenticate with Azure AD and get an access token that we can use to talk to the Office 365 Graph. The trick, is a little not-well known thing called Resource Owner grant.
I have a few links about the Resource Owner grant type at the end. Basically, this grant_type lets you use username/password to obtain an access token.
First of all we will setup Azure App registration.
We need the permission to Read and Write All groups (Group.ReadWrite.All).
If you are familiar with it, just skip ahead to the code section.
If not, you need to follow the below steps:
Once logged in, go to the App registration page as below:
Azure Active Directory page > App registrations > New Application registration.
Inside that, enter your details by providing some name and a valid Sign-on URL. Keep the Application type as Web App / API. Then click on Create. See below screengrab :
Once the application is created, navigate to it.
Please copy the application ID. This will be our client Id.
Now, go to the required permission and click on Add.
Inside the delegated permissions, click on the Read and write all groups
Click the awesome Grant Permissions button at the top of the permissions registration, this grants it for users in your Active Directory.
You will need some clientsecrets – create them from Keys. I like them not expiring for a long time. So I pick the Never expires option. It’ll expire when I’m long gone.
Copy down your ClientSecret.
Also, copy the Application ID which will be you client Id.
Now, lets do some coding 🙂
For this demo purposes, I am using a console application.
You will need the below Nuget packages:
We are going to make use to PnP Core’s UnifiedGroupsUtility.CreateUnifiedGroup method to create a Unified group.
We are also going to make a POST request to get the Graph API access token, for that we are going to make use of the
First we will create a class named AuthenticationResponse to map the JSON response.
Now, in our main method, it will be as below:
Done. This will create a Modern Unified team site with Office 365 group enabled.
References – Provisioning a “modern” team site programmatically