{"componentChunkName":"component---src-templates-blog-post-js","path":"/blog/power-automate-http-entra-id-apis-protegidas/","result":{"data":{"markdownRemark":{"frontmatter":{"title":"Power Automate: HTTP with Microsoft Entra ID para chamar APIs protegidas","description":"Pare de guardar segredos em fluxos: aprenda a autenticar o action HTTP with Microsoft Entra ID em APIs protegidas sem client secret, com managed identity e escopos corretos.","date":"04 de dezembro de 2026","thumbnail":null},"html":"<p>Chamar uma API protegida a partir de um fluxo parece trivial até o momento em que você precisa de autenticação OAuth. A reação mais comum — e mais perigosa — é fazer um action HTTP genérico que primeiro obtém um token via <code>POST</code> no endpoint <code>/oauth2/v2.0/token</code>, colando <code>client_id</code> e <code>client_secret</code> direto no corpo da requisição. Funciona na demo, mas joga segredos em texto claro dentro da definição do fluxo, exportados em toda solução e visíveis no run history. Existe um caminho melhor e nativo: o action <strong>HTTP with Microsoft Entra ID</strong> (antigo HTTP with Azure AD).</p>\n<p><strong>O que o HTTP with Microsoft Entra ID resolve</strong></p>\n<p>Esse action é um conector premium que encapsula o fluxo OAuth 2.0 inteiro. Você configura uma <em>connection</em> uma única vez, informando duas URIs de recurso (a <em>Base Resource URL</em> e a <em>Microsoft Entra Resource URI</em> — o App ID URI ou o GUID do recurso alvo), e autentica essa connection com uma identidade. A partir daí, cada chamada que você faz pelo action já vai com um <code>Authorization: Bearer &#x3C;token></code> válido, renovado automaticamente pela plataforma. Você nunca manipula o token, nunca guarda <code>client_secret</code> no fluxo e nunca precisa tratar expiração/refresh manualmente.</p>\n<p>A diferença prática em relação ao action HTTP puro:</p>\n<ul>\n<li><strong>HTTP puro</strong>: você é responsável por obter o token, armazenar o segredo, renovar antes de expirar e proteger tudo isso. Segredo acaba em environment variable (melhor) ou hardcoded (pior).</li>\n<li><strong>HTTP with Microsoft Entra ID</strong>: a connection carrega a identidade; o action só precisa de method, URL e body. Zero gestão de token no fluxo.</li>\n</ul>\n<p><strong>Os dois modos de identidade da connection</strong></p>\n<p>Ao criar a connection, você escolhe como ela se autentica, e essa é a decisão de arquitetura mais importante:</p>\n<ol>\n<li><strong>Em nome de um usuário (delegated)</strong>: a connection usa a identidade do usuário que a criou, via consentimento interativo. O token carrega as permissões <em>delegated</em> desse usuário no recurso alvo. É simples, mas acopla o fluxo a uma conta nominal — se o usuário sai da empresa ou tem a senha trocada/MFA reconfigurado, o fluxo quebra. Para automações críticas de produção, isso é um ponto único de falha humano.</li>\n<li><strong>Como identidade de serviço (application/managed identity)</strong>: quando disponível no seu ambiente, a connection usa uma identidade gerenciada, sem usuário por trás. O token carrega permissões <em>application</em> (app roles), concedidas via admin consent no app registration do recurso. É o modelo correto para integração sistêmica — sem conta nominal, sem senha para rotacionar, sem MFA no meio.</li>\n</ol>\n<p>Sempre que a API destino suportar app roles e você estiver chamando um serviço (não agindo em nome de uma pessoa específica), prefira identidade de serviço. Reserve delegated para cenários em que a API precisa saber <em>qual usuário</em> está pedindo e aplicar permissões por usuário.</p>\n<p><strong>Configurando o recurso do lado da API</strong></p>\n<p>O action não é mágica: ele pede um token para um recurso que precisa existir no Entra ID. Para uma Azure Function protegida por Easy Auth, uma Logic App standard, ou uma API custom publicada atrás do Entra, o passo prévio é ter um <em>app registration</em> que exponha a API com um <strong>App ID URI</strong> (algo como <code>api://&#x3C;guid></code> ou <code>https://contoso.com/minhaapi</code>). Esse App ID URI é exatamente o que vai no campo <em>Microsoft Entra Resource URI</em> do action.</p>\n<ul>\n<li>Para delegated, exponha um <em>scope</em> (ex.: <code>access_as_user</code>) na aba Expose an API e garanta o consentimento.</li>\n<li>Para application, defina <strong>app roles</strong> na manifest do app registration do recurso, atribua a role à identidade chamadora (o service principal da connection) e faça admin consent. Sem a role atribuída, o token sai sem a claim e a API retorna 403 mesmo com token \"válido\".</li>\n</ul>\n<p>Um erro clássico aqui é pedir token com o escopo errado. Para app roles, o escopo é sempre <code>&#x3C;AppIdUri>/.default</code> — não um scope nominal. A plataforma monta isso a partir da Resource URI que você configurou, por isso preenchê-la corretamente é o que faz ou quebra a chamada.</p>\n<p><strong>Armadilhas de produção</strong></p>\n<ul>\n<li><strong>Dono da connection é o dono do acesso</strong>: em modo delegated, quem criou a connection empresta a própria identidade e permissões. Documente isso e, de preferência, use uma conta de serviço dedicada e licenciada em vez da conta pessoal de um dev.</li>\n<li><strong>Connection references em ALM</strong>: ao exportar a solução, a connection não vai junto — vai a <em>connection reference</em>. No ambiente de destino, alguém precisa criar/religar a connection e consentir. Parametrize isso nos deployment settings do pipeline, senão o fluxo importado fica órfão.</li>\n<li><strong>Conector premium</strong>: o HTTP with Microsoft Entra ID consome licença premium, igual ao HTTP puro. Não é uma forma de escapar de custo de conector.</li>\n<li><strong>403 vs 401</strong>: 401 normalmente é token ausente/recurso errado (Resource URI incorreta); 403 é token válido sem a permissão/role correta. Diagnostique decodificando o <code>aud</code> e as claims de role/scope do token — mas lembre que, no action nativo, você nem vê o token, então o teste é feito do lado da API (logs do Easy Auth / App Insights).</li>\n<li><strong>Audience precisa bater</strong>: o <code>aud</code> do token emitido tem que ser exatamente o recurso que a API valida. Divergência entre o App ID URI configurado e o que a API espera é a causa silenciosa mais comum de 401.</li>\n</ul>\n<p><strong>Quando ainda faz sentido o HTTP puro</strong></p>\n<p>Se a API externa não vive no Entra ID — autentica por API key em header, OAuth com um identity provider de terceiros, ou basic auth — o action Entra não serve, e aí o caminho é HTTP puro com o segredo guardado em environment variable do tipo Secret (apoiada em Azure Key Vault), nunca hardcoded. E quando a lógica de autenticação fica realmente complexa (token exchange, on-behalf-of encadeado, mTLS), o melhor é empurrar a chamada para uma Azure Function que resolve a autenticação com managed identity do próprio Azure e expor um endpoint simples para o fluxo consumir.</p>\n<p>Tratar autenticação como configuração de connection, e não como passos manuais dentro do fluxo, é o que separa uma automação que sobrevive a uma troca de senha de uma que quebra no pior momento. Se a sua empresa opera integrações críticas em Power Automate e quer eliminar segredos espalhados pelos fluxos, a Dynamic Soluções ajuda a desenhar essa camada de identidade e a governança de connections/connection references em ALM.</p>\n<p>Calling a protected API from a flow looks trivial until the moment you need OAuth authentication. The most common — and most dangerous — reaction is to build a generic HTTP action that first fetches a token with a <code>POST</code> to the <code>/oauth2/v2.0/token</code> endpoint, pasting <code>client_id</code> and <code>client_secret</code> straight into the request body. It works in the demo, but it drops secrets in clear text inside the flow definition, exported in every solution and visible in the run history. There's a better, native path: the <strong>HTTP with Microsoft Entra ID</strong> action (formerly HTTP with Azure AD).</p>\n<p><strong>What HTTP with Microsoft Entra ID solves</strong></p>\n<p>This action is a premium connector that wraps the entire OAuth 2.0 flow. You configure a <em>connection</em> once, providing two resource URIs (the <em>Base Resource URL</em> and the <em>Microsoft Entra Resource URI</em> — the App ID URI or the target resource GUID), and you authenticate that connection with an identity. From then on, every call you make through the action already carries a valid <code>Authorization: Bearer &#x3C;token></code>, refreshed automatically by the platform. You never handle the token, never store a <code>client_secret</code> in the flow, and never deal with expiration/refresh by hand.</p>\n<p>The practical difference versus the raw HTTP action:</p>\n<ul>\n<li><strong>Raw HTTP</strong>: you're responsible for fetching the token, storing the secret, refreshing it before expiry, and protecting all of it. The secret ends up in an environment variable (better) or hardcoded (worse).</li>\n<li><strong>HTTP with Microsoft Entra ID</strong>: the connection carries the identity; the action only needs method, URL and body. Zero token management in the flow.</li>\n</ul>\n<p><strong>The two identity modes of the connection</strong></p>\n<p>When you create the connection, you choose how it authenticates, and that's the most important architecture decision:</p>\n<ol>\n<li><strong>On behalf of a user (delegated)</strong>: the connection uses the identity of the user who created it, via interactive consent. The token carries that user's <em>delegated</em> permissions on the target resource. It's simple, but it couples the flow to a named account — if the user leaves the company or has the password reset / MFA reconfigured, the flow breaks. For critical production automations, that's a single human point of failure.</li>\n<li><strong>As a service identity (application/managed identity)</strong>: when available in your environment, the connection uses a managed identity, with no user behind it. The token carries <em>application</em> permissions (app roles), granted via admin consent on the resource's app registration. This is the correct model for systemic integration — no named account, no password to rotate, no MFA in the middle.</li>\n</ol>\n<p>Whenever the target API supports app roles and you're calling a service (not acting on behalf of a specific person), prefer the service identity. Reserve delegated for scenarios where the API needs to know <em>which user</em> is asking and apply per-user permissions.</p>\n<p><strong>Configuring the resource on the API side</strong></p>\n<p>The action isn't magic: it requests a token for a resource that must exist in Entra ID. For an Azure Function protected by Easy Auth, a standard Logic App, or a custom API published behind Entra, the prerequisite is an <em>app registration</em> that exposes the API with an <strong>App ID URI</strong> (something like <code>api://&#x3C;guid></code> or <code>https://contoso.com/myapi</code>). That App ID URI is exactly what goes into the action's <em>Microsoft Entra Resource URI</em> field.</p>\n<ul>\n<li>For delegated, expose a <em>scope</em> (e.g. <code>access_as_user</code>) on the Expose an API tab and ensure consent.</li>\n<li>For application, define <strong>app roles</strong> in the resource app registration's manifest, assign the role to the calling identity (the connection's service principal) and perform admin consent. Without the role assigned, the token comes out without the claim and the API returns 403 even with a \"valid\" token.</li>\n</ul>\n<p>A classic mistake here is requesting the token with the wrong scope. For app roles, the scope is always <code>&#x3C;AppIdUri>/.default</code> — not a named scope. The platform builds this from the Resource URI you configured, which is why filling it correctly is what makes or breaks the call.</p>\n<p><strong>Production pitfalls</strong></p>\n<ul>\n<li><strong>The connection owner owns the access</strong>: in delegated mode, whoever created the connection lends their own identity and permissions. Document this and, ideally, use a dedicated licensed service account rather than a dev's personal account.</li>\n<li><strong>Connection references in ALM</strong>: when you export the solution, the connection doesn't travel — the <em>connection reference</em> does. In the target environment someone must create/rebind the connection and consent. Parameterize this in the pipeline's deployment settings, otherwise the imported flow is orphaned.</li>\n<li><strong>Premium connector</strong>: HTTP with Microsoft Entra ID consumes a premium license, just like raw HTTP. It's not a way to escape connector cost.</li>\n<li><strong>403 vs 401</strong>: 401 usually means a missing token / wrong resource (incorrect Resource URI); 403 means a valid token without the correct permission/role. Diagnose by decoding the token's <code>aud</code> and role/scope claims — but remember that with the native action you don't even see the token, so testing happens on the API side (Easy Auth logs / App Insights).</li>\n<li><strong>The audience must match</strong>: the <code>aud</code> of the issued token has to be exactly the resource the API validates. A mismatch between the configured App ID URI and what the API expects is the most common silent cause of 401.</li>\n</ul>\n<p><strong>When raw HTTP still makes sense</strong></p>\n<p>If the external API doesn't live in Entra ID — it authenticates by API key in a header, OAuth with a third-party identity provider, or basic auth — the Entra action doesn't help, and the path is raw HTTP with the secret stored in a Secret-type environment variable (backed by Azure Key Vault), never hardcoded. And when the authentication logic gets truly complex (token exchange, chained on-behalf-of, mTLS), it's better to push the call into an Azure Function that resolves authentication with the Azure managed identity itself and exposes a simple endpoint for the flow to consume.</p>\n<p>Treating authentication as connection configuration, not as manual steps inside the flow, is what separates an automation that survives a password change from one that breaks at the worst moment. If your company runs critical integrations in Power Automate and wants to eliminate secrets scattered across flows, Dynamic Soluções helps design this identity layer and the governance of connections/connection references in ALM.</p>"}},"pageContext":{"slug":"/blog/power-automate-http-entra-id-apis-protegidas/","previousPost":null,"nextPost":{"frontmatter":{"title":"Dataverse: custom APIs vs actions para contratos de serviço reutilizáveis"},"fields":{"slug":"/blog/dataverse-custom-api-vs-custom-action-contratos-servico/"}}}},"staticQueryHashes":["2269431855"]}