How to Authenticate for Azure Functions using Entra ID

Young, Charles 5 Reputation points
2023-11-05T20:34:37.8233333+00:00

Hello,

I am trying to run an Azure Function as an API between a React Native Application and a Microsoft SQL database. I want users to be able to log in with Microsoft credentials and access data. I have an access token from an app registration (named Bear Necessities AD) in Entra ID using the following code.

  const getSession = async () => {
    const cv = await Crypto.digestStringAsync(
      Crypto.CryptoDigestAlgorithm.SHA256,
      Math.random().toString(36).substr(2) + Date.now().toString(36)
    );
    const d = await AuthSession.fetchDiscoveryAsync(domain);
    const cc = await base64URLEncode(cv);

    const authRequestOptions: AuthSession.AuthRequestConfig = {
      prompt: AuthSession.Prompt.Login,
      responseType: AuthSession.ResponseType.Code,
      scopes: scopes,
      usePKCE: true,
      clientId: ADConfig.applicationClientID,
      //clientSecret: ADConfig.secretValue,
      redirectUri: __DEV__ ? redirectUrl : redirectUrl + "example",
      state: ADConfig.state,
      codeChallenge,
      codeChallengeMethod: AuthSession.CodeChallengeMethod.S256,
    };
    const authRequest = new AuthSession.AuthRequest(authRequestOptions);
    $authRequest(authRequest);
    $discovery(d);
    $codeChallenge(cc);
  };

  const getCodeExchange = async () => {
    const tokenResult = await AuthSession.exchangeCodeAsync(
      {
        code: authorizeResult.params.code,
        clientId: ADConfig.applicationClientID,
        redirectUri: __DEV__ ? redirectUrl : redirectUrl + "example",

        extraParams: {
          code_verifier: authRequest.codeVerifier,
          grant_type: "authorization_code",
        },
      },
      discovery
    );
    const { accessToken, refreshToken, issuedAt, expiresIn } = tokenResult;
    $token(tokenResult);
    console.log(accessToken);
    console.log(refreshToken);
    console.log(issuedAt);
    console.log(expiresIn);
  };

I have added Microsoft as the identity provider for the function app, using the same application registration. function auth settingss enter image description here

Here is my attempt to expose the api: enter image description here enter image description here

Here is the code I use to call the function:

const callAzureFunction = async () => {
    const functionUrl =
      "https://bearnecessititesfunctionapp.azurewebsites.net/api/HelloWorld?code=XXXXXXX==";

    try {
      const response = await fetch(functionUrl, {
        method: "POST", // Or 'POST', 'PUT', etc., depending on your Azure Function configuration
        headers: {
          Authorization: `Bearer ${token.accessToken}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: "Test",
        }),
      });

      if (response.ok) {
        const data = await response.json();
        console.log("Response from Azure Function:", data);
        // Process the data received from the Azure Function
        console.log(data);
      } else {
        console.error("Error calling Azure Function:", response.status);
        // Handle error responses
      }
    } catch (error) {
      console.error("Error:", error);
      // Handle any network errors or exceptions
    }
  };

I can call the function when authentication is disabled, but I get the set 401 error when it is enabled. Am I able to authenticate using the access token I already have? If so, what could be wrong here?

Thank you for your time!

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,253 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,653 questions
{count} vote

1 answer

Sort by: Most helpful
  1. MayankBargali-MSFT 70,751 Reputation points
    2023-11-13T09:06:28.2+00:00

    @Young, Charles You can find the key or the function URL by navigating to your individual function and then go to Code + Test and click on Get function url.

    It will have the link and key that would be used to authenticate your function app.

    User's image

    Regarding your question about app registrations, you can use the same app registration for both your React Native app and your Azure Function app. You do not need to create separate app registrations. However, you may need to configure the app registration differently for each scenario. For example, you may need to configure different redirect URIs for your React Native app and your Azure Function app.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.