Creating an Azure Function using Microsoft Graph API
Azure functions is a cloud based system which fulfills all the requirements to run an application in terms of infrastructure and resources. They are quite light weight and very handy because if you want to perform a certain task through a piece of code you don’t need to worry about its deployment and environment. You can only focus on writing the code and publish the function app. You can use it through a azure generated link, and done.
The best part is, it supports multiple languages. Such as, C#, JAVA, JavaScript, PowerShell, Python, Go/Rust/ TypeScript. So, you can use any language in which you are comfortable writing the code.
The azure function can be developed in multiple ways. It can be developed on Visual Studio, Visual Studio Code, or on premises directly in the azure environment too.
Today, we will be looking into an example of azure function app which will be composed following components:
- Developing it locally on visual studio
- Authentication with Microsoft
- Usage of Graph API
- Getting the data from azure active directory using Graph API
This function app will retrieving the user profile from azure active directory of an authenticated user using GraphAPI.
Now, lets dive in to the actual implementation.
Function App Example
Step 1 | Configurations in Azure Portal
To build an azure function app you need azure subscription. For developers, there is a trial available as well.
Go to function apps in azure, and click on +create.
After that this page will appear
Lets go through each of the field there:
- Subscription — Select the subscription you have
- Resource Group — Either select an existing resource group, or create a new one
- Publish — Either you want to publish the code, or use a docker container.
- Runtime stack — It opens the drop down of all the languages it support.
- Verison — Select the verison of the runtime stack
- Operating System — Select on which operating system you will be developing it
- Plan — Select a suitable plan, for the app scaling
After this, select next. And, the following page will appear.
In Fig 4 you are just selecting the storage account for your function app.
The next steps of networking, monitoring, deployment, tags are common required fields. After all that, review the details and click on create.
Creating an App Registration
We will need an app registration to be used in the authentication. So for that we can either create it on the go when creating the authentication. Or, create it before hand and select the existing app registration in authentication. I am gonna create the app registration before. Generate the client secret, copy it and save. Otherwise, it won’t be visible later.
After the creation of function app. You need to enable authentication for it. Lets see authentication options. When you click on add identity provider it will open a page and provide you a drop down of options. For this app, I am using Microsoft Identity Provider.
Additionaly, to allow GraphAPI to read the user profile. Go to the API Permissions of your app registration. Add User.ReadAll permission with admin consent as shown in Fig 7.
Step 2 | Coding in Visual Studio
Create a project of Azure Functions.
Here in Fig 9, I have selected Authorization level anonymous. Basically, there are three types of authorization.
- Anonymous — No API key is required.
- Function — A function-specific API key is required. This is the default value when a level isn’t specifically set.
- Admin — The master key is required.
For the purpose of keeping it simple, the anonymous level is used.
After the creation of the project, files will be automatically generated. The file named as Function1.cs is the one in which the business logic of the function is written.
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log, ClaimsPrincipal claimIdentity)
{
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
Constants.TenantId, Constants.AppId, Constants.ClientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, Constants.scopes);
var user = await graphClient.Users[claimIdentity.Identity.Name].GetAsync();
var json = Newtonsoft.Json.JsonConvert.SerializeObject(user);
return new OkObjectResult(json);
}
Previously we setup microsoft identity provider as authentication method in azure function. Now, in the following code. ClaimPrincipal is returning us the identity of the logged in user.
(For constants, I have created a Constants file separately)
internal class Constants
{
public static string AppId = "<YOUR APP ID>";
public static string TenantId = "<YOUR TENANT ID>";
public static string ClientSecret = "<YOUR CLIENT SECRET>";
public static string TenantName = "<YOUR TENANT NAME>";
public static string [] scopes = new[] { "https://graph.microsoft.com/.default" };
}
Using ClientSecretCredential we are gonna authenticate our app registration. As you have seen we are giving here TenantId, AppId(ClientId), ClientSecret, and options. Then, we are using the GraphServiceClient to access the GraphApi, to fetch the user from azure active directory. For that, we have passed the clientSecretCredential, scope in it to initialize the object. Next, we are using that client and the claim principal id to fetch that logged in user profile.
After that, we have converted that user object to json to return.
Finally, we publish the app as presented in Fig 10.
Step 3 | Testing the Function
Now, go back to the azure portal inside the function app. There, your newly created function will be visible like shown in Fig 11.
Click on the name of your function. The following screen will appear as shown in Fig 12.
Click on Get Function Url, copy the Url and run in the browser.
First it will prompt you to enter your Microsoft credentials. Then it will return your user profile in the form of json.
Conclusion
In this article I have given a basic example of azure function in C#, presenting the concept of authentication, graph api and azure function development in visual studio. Feel free to explore more in depth, and share your findings.