Search code examples
oauth-2.0azure-functionsmicrosoft-identity-platform

Time triggered Azure function - Bearer token generation to call a protected API


I am trying to write an Azure function which is time triggered and runs every 10 minutes.

The function needs to call an API which expects a bearer token.

How do I generate the token? Since it is time based, I can't have a user to login and give function authorization token by signing into MS Identity platform which can be used to get the access token.


Solution

  • You just need to get the token by the code below in your timer trigger function:

    HttpClient client = new HttpClient();
    var values = new Dictionary<string, string>
    {
        { "client_id", "<your app client id>" },
        { "scope", "<scope>" },
        { "username", "<your user name>" },
        { "password", "<your password>" },
        { "grant_type", "password" },
    };
    
    var content = new FormUrlEncodedContent(values);
    
    var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
    
    var responseString = await response.Content.ReadAsStringAsync();
    

    Then you need to parse responseString(in json type) and use the access token in it to request your api.

    Update:

    Get token by client credential:

    HttpClient client = new HttpClient();
    var values = new Dictionary<string, string>
    {
        { "client_id", "<your app client id>" },
        { "scope", "<scope>" },
        { "client_secret", "<your app client secret>" },
        { "grant_type", "client_credentials" },
    };
    
    var content = new FormUrlEncodedContent(values);
    
    var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
    
    var responseString = await response.Content.ReadAsStringAsync();