Azure Static Web App Authenticate Service Principal

Pascal Kröger 0 Reputation points
2024-07-31T12:19:26.08+00:00

Hello,

we are using Azure Static Web App to host a Rest API (Data API Builder)

We have configured custom Entra ID Authentication on the static web app that works fine for interactive user authentication (e.g a user calls the web app via his. browser).

However when trying to access the api programatically we can't seem to get the authentication done.

I try to get a token from Entra using a Service Principal.

https://login.microsoftonline.com/tenantid/oauth2/v2.0/token

client_id:<<>>

client_secret:<<>>

grant_type:client_credentials

scope:api://<<custom auth app reg id>>/.default

When trying to access the API using the returned token we get a 401. After some digging I realized that even for users there is no access token sent to the static web app but a cookie called "StaticWebAppsAuthCookie" with some value that seems to contain the authentication info.

Now the question how can I authenticate against a custom Entra ID protected static web app using a service principal?

Azure Static Web Apps
Azure Static Web Apps
An Azure service that provides streamlined full-stack web app development.
856 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,698 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Marilee Turscak-MSFT 36,496 Reputation points Microsoft Employee
    2024-07-31T20:50:59.02+00:00

    Hi @Pascal Kröger ,

    I understand that you are receiving a 401 Unauthorized response when trying to access the Rest API.

    The authentication also needs to be added to the staticwebapp.config.json, and the user needs to have the allowed role of authenticated or anonymous, as described here.

    In addition, if you have linked a function app to your Azure Static Web App, I would recommend double-checking to ensure that the auth level of the function is explicitly set. I saw another user who faced this exact same error with the Data API Builder and the StaticWebAppsAuthCookie not completing the authentication. This was because the auth level of the function was not set explicitly and it defaulted to AuthLevel.FUNCTION, even though AuthLevel.ANONYMOUS was required in the simple auth flow.

    Finally, I would recommend checking if the request includes a header with a key of X-MS-API-ROLE and a value that matches a role name specified in your entity configuration rules, as shared by Deepanshukatara-6769 in the post.

    Let me know if this helps and if you still face this issue.

    If the information helped you, please Accept the answer. This will help us and improve searchability for others in the community who may be researching similar questions.

    0 comments No comments