0

I have an Azure Function which has authentication enabled and set to require an identity provider:

App Service authentication: Enabled Restrict access: Require authentication Unauthenticated requests: Return HTTP 401 Unauthorized Token store: Enabled

Identity provider - App (client) ID (Name of App Removed): Client ID Removed Client Secret Setting Name: Microsoft_Provider_Authentication_Secret

enter image description here

When I use Power Automate to POST to the HTTP function it works. This tells me the security is set up and working as expected. When I try and POST to the function directly from PowerShell using my desktop, I get a 401 unauthorized. This is a GCCH environment.

This is the PowerShell code where I get an oath token and am trying to use that to POST to the HTTP function. I tried using the HTTP URL with and without the 'code=' and neither worked.

#These URLs are used to access get the token; scope has not been required is uses the app ID 
    $loginURL   = "https://login.microsoftonline.us"
    $resource   = "https://graph.microsoft.us"
    $Tenant      = "mytenant.onmicrosoft.us"
    $ClientID = "removed"
    $Secret="removed"
    $fcnKey = "removed"
    $fcnURL = "https://removed?"   #Azure function url without the code at the end

    $AuthBody = @{
        grant_type="client_credentials";
        resource=$resource;
        client_id=$ClientID;
        client_secret=$Secret}

    $Oauth = Invoke-RestMethod -Method POST -Uri $loginURL/$Tenant/oauth2/token?api-version=1.0 -Body
    $AuthBody -ContentType "application/x-www-form-urlencoded"
    $AuthToken = @{
        'Authorization'="$($Oauth.token_type) $($Oauth.access_token)";
        'Content-Type' = "application/json";
        'x-functions-key' = $fcnkey;}

    #This returns a 401 unauthorized
    Invoke-RestMethod -Headers $AuthToken -Uri $fcnURL -Method POST

    #This also returns a 401 unauthorized
    $AuthToken = @{
        'Authorization'="$($Oauth.token_type) $($Oauth.access_token)";
        'Content-Type' = "application/json";}

    $FullURL = "https://removed?code=removed"
    Invoke-RestMethod -Headers $AuthToken -Uri $fullURL -Method POST
FlorH
  • 1
  • 1
  • What type of authentication is being used. Working code is probably trying more than one type. You are probably using wrong type. See : https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows – jdweng Jan 06 '23 at 11:04

1 Answers1

0

As @jdweng suggested to check the type of authentication and the process of authorization in this MS Doc of Azure AD Authentication Flows.

Check if the below steps help to fix the issue:

  • Make Sure you entered the "App ID URI" in the "Allowed Token Audiences" Box.
  • Same App ID URI should be used for acquiring the token.
  • Refer to the Similar issue-solutions where 401 Unauthorized error is registered on enabling the App service Authentication on Azure Function App such as MSQ&A337577, SO Questions 67957353 and 55226143.