Translate

Mostrando postagens com marcador integration. Mostrar todas as postagens
Mostrando postagens com marcador integration. Mostrar todas as postagens

terça-feira, 11 de agosto de 2026

Fixing "Insufficient privileges" on D365 Finance and Operations Batch SharePoint Connections

D365F&O Tenant Migration

The symptom

While troubleshooting a custom SysOperation batch process that uploads a generated CSV file to a SharePoint document library (via SharePointDocumentStorageProvider) after a Tenant Migration, I ran into an upload failure that looked like this:

Upload failed: Exception has been thrown by the target of an invocation.
Inner: An unknown error occurred while communicating with the SharePoint server '<tenant>.sharepoint.com'.

The exception itself is unhelpful — it's the generic wrapper message that the SharePoint client SDK returns whenever the underlying HTTP call fails, without exposing the actual status code or response body.

The first clue came from Document management parameters (Organization administration > Document management > Document management parameters > SharePoint). This page has two separate connection tests:

  • Test interactive SharePoint connection — succeeded
  • Test batch SharePoint connection — failed with "You are not authorized to connect to '<tenant>.sharepoint.com'"

That asymmetry was the key diagnostic signal. If the interactive test works but the batch test doesn't, the problem isn't the SharePoint site, the folder path, or the Document Type configuration — it's specifically about how non-interactive (application-only) calls authenticate.

Root cause

Interactive connections use the signed-in user's delegated permissions — essentially riding on the user's existing Microsoft 365 license and SharePoint access, just like a browser session would.

Batch connections are different. Since Microsoft deprecated the old Microsoft-managed high-trust connection between finance and operations environments and SharePoint (this affects environments on version 10.0.40 and later that have SharePoint user authentication enabled), batch jobs authenticate as an application rather than as a user. This means the finance and operations service principal needs its own application-level grant to talk to SharePoint Online — and that grant is not provisioned automatically. A tenant administrator has to assign it manually once per tenant.

If nobody has performed this one-time setup, every batch/non-interactive call to SharePoint — including custom X++ code using SharePointDocumentStorageProvider, and the built-in Export attachments feature — will fail with exactly the vague error shown above, while everything that goes through an interactive user session keeps working fine. This makes the problem easy to misdiagnose as a networking, firewall, or tenant-migration issue when it's actually a missing permission grant.

The fix

The fix is to grant the Microsoft Dynamics ERP first-party service principal an application permission (Sites.ReadWrite.All) against the SharePoint Online first-party service principal, in the target tenant. Both service principals already exist in every tenant that runs finance and operations and SharePoint — there's nothing to register or create.

Option A — PowerShell (Microsoft Graph SDK)

This is Microsoft's documented approach. Run it once, as a Global Administrator (or a role with Application.ReadWrite.All), against the tenant that hosts the finance and operations environment's SharePoint site:

Import-Module Microsoft.Graph.Applications

# Replace with your tenant
Connect-MgGraph -TenantId <yourtenant>.onmicrosoft.com -Scopes 'Application.ReadWrite.All'

# These AppIds are fixed first-party application IDs — they do not change between tenants
$erpServicePrincipal = Get-MgServicePrincipal -Filter "AppId eq '00000015-0000-0000-c000-000000000000'"
$sharePointServicePrincipal = Get-MgServicePrincipal -Filter "AppId eq '00000008-0000-0ff5-ci00-000000000000'"
$spAppRole = $sharePointServicePrincipal.AppRoles | Where-Object { $_.Value -eq 'Sites.ReadWrite.All' }

# Assign the SharePoint 'Sites.ReadWrite.All' application role to the Dynamics ERP service principal
New-MgServicePrincipalAppRoleAssignedTo `
    -ServicePrincipalId $erpServicePrincipal.Id `
    -PrincipalId $erpServicePrincipal.Id `
    -ResourceId $sharePointServicePrincipal.Id `
    -AppRoleId $spAppRole.Id

Option B — Microsoft Graph Explorer (no local PowerShell needed)

If PowerShell isn't installed locally, or a policy restricts running scripts on your machine, the exact same operation can be done through Graph Explorer, signed in as a Global Administrator:

1. Find the Dynamics ERP service principal

GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=appId eq '00000015-0000-0000-c000-000000000000'

Copy the id from the response — this is erpServicePrincipalId.

2. Find the SharePoint Online service principal

GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=appId eq '00000008-0000-0ff5-ci00-000000000000'

Copy the idsharePointServicePrincipalId — and, from the appRoles array in the same response, find the entry where "value": "Sites.ReadWrite.All" and copy its id — this is appRoleId.

Note: Graph Explorer's default permission set (User.Read) won't be enough for either of these steps. Under Modify permissions, consent to Application.ReadWrite.All first — as a Global Admin you can grant this directly from the same screen.

3. Grant the permission

POST https://graph.microsoft.com/v1.0/servicePrincipals/{erpServicePrincipalId}/appRoleAssignments

Request body:

{
  "principalId": "{erpServicePrincipalId}",
  "resourceId": "{sharePointServicePrincipalId}",
  "appRoleId": "{appRoleId}"
}

A 201 Created response confirms the grant succeeded.

Verifying the fix

Back in Document management parameters > SharePoint, run Test batch SharePoint connection again. It should now report success, matching the interactive test.

A security note

Sites.ReadWrite.All is a broad grant — it gives the finance and operations application read/write access to every SharePoint site in the tenant, not just the specific document library used by a given integration. There's no officially documented narrower alternative for this particular first-party grant (the more restrictive Sites.Selected model applies to apps you register and control yourself, not to this Microsoft-managed service principal). If your organization has strict least-privilege requirements for SharePoint, this is worth flagging to your security team as an accepted trade-off and revisiting if Microsoft introduces a more granular option in the future.

Conclusion

When a finance and operations environment can reach SharePoint interactively but not from batch, don't waste time chasing networking, DNS, or tenant-migration theories first — check whether the one-time application consent for batch SharePoint access has actually been granted. This step is easy to miss because it doesn't live in D365 F&O at all: it's an Entra ID (Azure AD) application permission that must be granted once per tenant, and there's no button for it in the finance and operations client. Whether you use PowerShell or Graph Explorer, the operation is a single, five-minute application role assignment — but until it's done, every non-interactive SharePoint call from your environment, including custom integrations and the built-in Export attachments feature, will keep failing with the same unhelpful "unknown error" message.

quarta-feira, 25 de junho de 2025

Criando um Azure App Registration para ser usado na integração entre LCS <> DevOps <> Azure.

 Processo simples e descomplicado, vamos criar um App Registration no Azure para que possamos integrar o LCS, o DevOps e também o Azure para fins de automação entre estas plataformas como por exemplo, o upload de pacotes gerados pelo Pipeline do DevOps e aplicação deste pacote em um determinado ambiente no LCS!

O primeiro passo é acessar o Azure e ir ao Entra ID. é isso mesmo, agora a gestão dos App Registrations fica dentro do Entra. Se você não tem acesso ao Entra, procure outra coisa pra fazer!


Escolha criar um novo App Registration, defina um nome coerente com a funcionalidade e escolha 


Depois de registrado, anote o Application (Client) ID.


Clique na opção "Authentication", deixe conforme a imagem abaixo, siga os numeros!!!

Agora clique em Certificates and Secrets, gere um Secret novo, defina o nome e prazo de vencimento. Salve cuidadosamento oque está no campo "Value". Vamos utilizado e muito. Se não salvar agora você será obrigado a gerar um novo secret.


Agora clique em API Permission, adicone um novo, selecione a opção do meio e clique em Dynamics Lifecicle Services.

Selecione Delegated Permission, marque a opção "user_impersonation" e clique em Add permission.
Clique em grant admin consent, confirme e pronto.

Veja que agora há um sinal verde de "Granted...".


Agora é só utilizar o App Registration do seu DevOps junto com uma "conta de serviço" que NÃO TENHA MFA habilitado!








sexta-feira, 5 de abril de 2013

Instalação Dynamics AX2012 R2. Parte 10 - Integração Com Project Server.

AAHAaaaaaaaaaaaaaaaaaa lelek lek lek lek!!!!!!!!!

Este post merece esse refrãozinho miserável que ficou impregnada na minha cabeça!!!!!

Finalmente consegui o tempo necessário para postar aqui como instalar e configurar os componentes de integração com o Project Server!

Para termos o AX2012 R2 integrado com o Project Server 2010 precisamos logicamente destes componentes corretamente instalados e acessíveis. A instalação do AX2012 R2 pode ser vista neste link. Para instalar o Project Server 2010 você pode consultar o TechNet ou em uma rápida pesquisa no Google você encontrará diversos tutoriais!

Tendo o Project Server 2010 e o Dynamics AX2012 R2 completamente instalados e totalmente acessíveis vamos instalar e configurar os componentes de AX para a integração com o Project Server.

Neste cenário vou utilizar todos os componentes necessários instalados em apenas 01 servidor virtual, este é o cenário mais fácil para esta instalação, para facilitar ainda mais eu vou utilizar o usuário administrator para as permissões. Logicamente em um cenário de produção haverão servidores diferentes dedicados a cada aplicação, neste cenário de produção as corretas contas de serviço dedicas deverão ser utilizadas, para mais detalhes consultem este White Paper.

Para começar inicie o setup do AX2012 R2 e na tela de seleção dos componentes marques os componentes referentes ao Project Server e clique em Next. Veja imagem abaixo:

O erro abaixo indica que um requisito está faltando, marque a opção e clique no botão configure.

Agora clique no botão Start e aguarde o final do processo de configuração. Clique no botão Close.

Validação OK, clique em Next.

Digite a senha correta para a conta bcproxy e clique em Next. Como havia dito anteriormente eu estou utilizando a conta Administrator para todos os serviços. Não faça isso em produção.

Agora digite uma conta e senha dedicada ao serviço de sincronização que será criado nos serviços do Windows.Como havia dito anteriormente eu estou utilizando a conta Administrator para todos os serviços. Não faça isso em produção.

Selecione "Create a new queue", deixe as outras opções como na imagem abaixo e clique em Next.

Verifique a conta a ser utilizada para sincronização. Atenção nesta passo em ambientes de produção.

Agora preencha os campos abaixo conforme solicitado. Caso não saiba o nome do banco de dados de reports to Project Server consulte o White Paper indicado acima, lá está descrito como encontrar esta informação.

Validações ok, clique em Next.

 
Clique em Install.

 
Instalação ok, clique em Finish!
 
Após a instalação é necessário iniciar manualmente o serviço de sincronização, faça isso então uai!!!
 
Este passo você não encontrará em nenhum manual, portanto preste atenção a ele... ta prestando atenção? VC TA PRESTANDO ATENÇÃO?!!!!
 
Abra o Server Manager e expanda a opção Features > Message Queuing > Private Queues e clique com o botão direito do moue na opção "Microsoftdynamicsax".
 
Nas propriedades desta opção deixe a opção "jornal" habilitada. clique em apply e depois clique em ok.
 
Você realmente prestou atenção?! fez tudo certinho?! Então vamos para o próximo passo!!!
 
Agora abra o AX Client e acesse Administração do Sistema > Configuração > Integração do Microsoft Project Server > Configurações de integração e preencha os campos conforme solicitado. você precisará selecionar a empresa para qual a integração será habilitada e move-la da direita para a esquerda!


 
Com as configurações ok, clique no botão "Habilitar integração", este processo demora alguns minutinhos, fique de olho no "Status da integração", atualize-o utilizando o botão "Atualizar status. Quando o status estiver como concluído o processa estará finalizado e a integração desta empresa com o Project Server estará corretamente configurada. É necessário configurar os parâmetros de integração para cada empresa existente no AX a utilizar esta função!
 
Ainda no modulo de Administração do sistema você pode utilizar as 02 telas abaixo para efeitos de monitoramento dos Jobs de integração. talvez seja útil em caso de problemas na sincronização dos projetos!
 



Agora é só liberar a integração aos consultores de projetos para que eles façam seus testes!

Francisco Silva!