Skip to content Skip to sidebar Skip to footer

Baking Auth Into An Azure Function App: What's The Canonical Way?

I would like to make a function app that returns a duration until an event. The events are stored in a shared calendar in outlook. I can access the shared calendar using the graph

Solution 1:

You can implement that by client_credentials flow. Pls follow the steps below : 1. Register an Azure AD app and note its application ID. Granting Read Calendar permission of Microsoft Graph API : enter image description hereenter image description here Do remember click "Grant admin consent for your tenant" to finish the permission grant process. With this process done ,this app will have permission to read all users' calendar info in your tenant via graph API.

  1. Create a client secret for your app , and note it , we will use it later: enter image description here

Try the azure function code below :

import logging
import requests
import json
import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:

    tenantID = "<your tenant ID>"
    account = "<account in your tenant you want to share event>"
    appId= "<app ID you just registered >"
    appSecret = "<app secret you just created>"

    authUrl = 'https://login.microsoftonline.com/'+ tenantID +'/oauth2/token'
    body = "grant_type=client_credentials&resource=https://graph.microsoft.com&client_id="+ appId +"&client_secret=" + appSecret
    headers = {'content-type': 'application/x-www-form-urlencoded'}

    r = requests.post(authUrl, data=body, headers=headers)
    access_token = json.loads(r.content)["access_token"]

    graphURL = "https://graph.microsoft.com/v1.0/users/"+account+"/events?$select=subject,start"

    result =requests.get(graphURL,
    headers={'Authorization': 'Bearer ' + access_token}
    )

    #get all event results here and you can finish your logic below:
    eventResult = result.content


    return func.HttpResponse(str(eventResult))

Result : enter image description here As you can see you can get events form an account you specified . Of course you can do your own business logic after you get events in function. Hope it helps .

Post a Comment for "Baking Auth Into An Azure Function App: What's The Canonical Way?"