OAUTH / Azure Functions: Method to auth AAD user for endpoints that don't support service principals

Viewed 163

I've been leveraging Azure Function Apps to automate items in Azure. I currently have working functions that connect to Microsoft Graph, Resource Explorer, KV etc. using service principal / OAUTH client credentials flow (inside the function app). To call my function app, I've implemented implicit flow. While I'm not an expert at OAUTH, I am familiar enough now to get this configured and working.

However, there are Azure endpoints I need to use that don't support using a service principal token, they only support an actual AAD user requesting a token. Here's one that I want to run: Create synchronizationJob

If you look at the permissions section of the above link, you'll see that "application" is not supported. I did test this in a function: I can run these endpoints in Graph Explorer fine (as myself), but they fail in the function when using a token linked to a service principal.

Since this new automation is going to be an Azure Function (and not an interactive user), I can't use the authorization code flow. I need this service account's OAUTH to be non-interactive.

TL;DR

I can run the above endpoint in Azure's Graph Explorer just fine:

Azure Graph Explorer

since I'm authenticating as myself, and have a token generated based on my user ID. But for automating using Azure Functions where I need to use this endpoint (which doesn't support OAUTH using an SP), I need some way to have a back-end AAD user auth and pull a token that can be used to run the endpoint.

Any help is welcome! Feel free to tell me that I'm either missing something very basic, or not understanding a core principal here.

1 Answers

As juunas mentioned no guarantee that will work though, I test in my side and it seems doesn't work although I assigned "Global administrator" role to the service principal.

For your situation, you can request the access token in your function code and then use the access token to request the graph api.

Add the code like below in your function to get access token.

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();

var obj = JObject.Parse(responseString);
var accessToken = (string)obj["access_token"];

And then use the access token got above to request graph api.

Related