D365 Business Central: OAuth2 Setup and Automation – Part 5
Yo! Just wow.
We’re now at the fifth installment of this OAuth2 Setup and Automation arc, and I’m still thinking about what we might have missed and what we can dig deeper into.
If you spot anything, or wish me to cover something in our upcoming #BCSaturdayCodeHacks, Drop a comment down below. Let’s keep learning above and beyond MS Dynamics Business Central!
So here’s the setup and what we have learned so far,
After registering your Entra app in Part 4: Automate Entra App Registration Using Azure CLI, the next step is to retrieve an access token with no Postman and no UI clicks.
This part shows how to use PowerShell to request a token using the client credentials flow, then validate it against Business Central’s API.
This is the same flow used by background jobs, integrations, and headless scripts. It’s fast, repeatable, and ready for automation.
We’ve registered the app. We’ve assigned permissions. We’ve granted consent. Now what?
If we’re still manually grabbing tokens from Postman… we’re not done yet.
Overview: What This Covers
Alright, before we dive in, let’s set the stage.
Here’s a quick glance at what we’re about to explore. But first, I’m gonna make a few assumptions (if that’s okay of course)
- You’ve read Part 1 to Part 4 of this OAuth2 Setup and Automation arc, where we dive deep into the entire OAuth2 app registration workflow, test it and automate everything.
- You’ve got admin access to the target tenant
- You can copy and paste a few commands into the terminal without breaking a sweat
- You’ve got more than 5 minutes to waste, I mean to spare (lol HAHAHAHAHA)
Here’s what we’ll cover:
- Building the token request using Invoke-RestMethod
- Validating the token with a Business Central API call
Let’s suit up, grab and your snorkel and dive in. No extra oxygen for now, it will be quick.
Step-by-Step: Token Retrieval and Validation
Alright, let’s get this token, scripted, headless, and ready for real work.
What Does “Headless” Even Mean?
If you’re wondering what “headless” means, here’s the quick take
It’s a system that runs without a built-in user interface (UI). No buttons. No dashboards. Just raw API power.
What that looks like in practice:
- No built-in UI - The system doesn’t render visual components
- API-driven - All interactions happen via REST, GraphQL, or other APIs
- Front-end agnostic - You can build your own UI, CLI tools, or just script it straight
Now that we’ve got the concept down, let’s prep the credentials.
Prepare Your Credentials
In this session, here’s what we need.
This is your entry pass. Don’t lose it, don’t lend it.
Request the Token via PowerShell
Assuming you’ve already read Part 4: Automate Entra App Registration Using Azure CLI, where we covered how to open up a PowerShell terminal I won’t repeat that here. Let’s jump straight into the move
We will hit the v2 token endpoint, parse the bearer token which is the access_token key, and bam bam boom, we've got headless access.
If you wish to see the raw JSON response, Just output the $response variable.
$tenantId = "<your-tenant-id>"
$clientId = "<your-client-id>"
$clientSecret = "<your-client-secret>"
$scope = "https://api.businesscentral.dynamics.com/.default"
$body = @{
grant_type = "client_credentials"
client_id = $clientId
client_secret = $clientSecret
scope = $scope
}
$response = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Body $body -ContentType "application/x-www-form-urlencoded"
$accessToken = $response.access_token
Write-Host $accessToken
This sends a token request using the client credentials flow. If successful, $accessToken will hold your bearer token, ready to be used in API calls.
What Is Invoke-RestMethod?
As you saw in the code above, we used Invoke-RestMethod. So… what does it actually do?
It’s a PowerShell cmdlet that sends HTTP or HTTPS requests to RESTful web services. Think of it as your API Swiss Army knife, it’s got just enough blades to get the job done, whether you’re poking, patching, or pulling data from an endpoint (e.g. GET, POST, PATCH, etc). It automatically converts JSON/XML responses into native PowerShell objects.
How to Use Invoke-RestMethod and It's Core Syntax
Here’s the basic structure. It lets you poke an API endpoint through PowerShell, just like Postman, but scriptable:
Invoke-RestMethod -Uri "<endpoint>" -Method <GET|POST|PUT|PATCH|DELETE> -Headers <hashtable> -Body <payload>
These are the most common parameters:
- -Uri: The API endpoint
- -Method: HTTP method (defaults to GET)
- -Headers: Custom headers (e.g., Authorization)
- -Body: Payload for POST/PUT/PATCH
But if you wish to see the full list of parameters? Grab it here Invoke-RestMethod (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
Invoke-RestMethod: Authentication Options
Unfortunately, Not all Postman authentication types are supported in Invoke-RestMethod, but most are covered:
Now that you’ve got a bit of background on the Invoke-RestMethod cmdlet, let’s get back to the automation.
Validate the Token with Business Central
Assuming you’ve already configured your OAuth2 Entra App inside Business Central, you can now query the available APIs directly, no UI, no Postman, just pure script.
$headers = @{
Authorization = "Bearer $accessToken"
}
Invoke-RestMethod -Method Get -Uri "https://api.businesscentral.dynamics.com/v2.0/$tenantId/Production/api/v2.0/companies" -Headers $headers
Replace Production with your actual environment name.
That’s a wrap, same flow Microsoft uses under the hood for PTE publishing, just a different endpoint.
What Works in Practice
Here are a few habits that make this workflow reliable in real world automation:
- Store secrets securely e.g. environment variables or Azure Key Vault (We will cover this separately)
- Rotate secrets regularly
- Decode tokens to verify scopes and expiry
- Log token requests and API responses for traceability
Common Issues
Even with a solid setup, stuff breaks and things go south, which often beyond our control. So, here’s what usually goes wrong and how to fix it fast:
Pro Tip and Quick Win
Think of this as cheat codes for smoother automation, not obvious, but game changing once you know
Wrap this flow in a reusable PowerShell function, something like screams of what it does e.g. Get-BCGraphToken. That way, any script that needs access to Business Central can just call it and keep things clean and reusable.
TL;DR – What’s Next
You’ve now scripted how to grab a token using PowerShell and confirmed it works with Business Central’s API. This setup replaces Postman for headless automation and gives you full control over how tokens are handled.
Next and every Saturday, we’ll go beyond the docs, covering real-world API automation patterns that don’t show up in official guides but emerge from actual builds and implementation experience.
Teaser Post: There’s a Part 6, and even more coming in this OAuth2 setup and automation arc!
Support for the Community
If you’ve hit token errors, permission issues, or weird API behavior, drop a comment or raise a GitHub issue. I’ll keep this series updated as Microsoft evolves the identity platform.
♻️ Repost to support the Microsoft Dynamics 365 Community and follow Jeffrey Bulanadi for technical insights above and beyond Business Central, AL development, and scalable integration architecture.
Demo Repository
Explore the sample below based on what we covered here—headless token retrieval and how the actual PowerShell script here OAuth2 Setup and Automation – Part 5 on GitHub
Helpful References
Invoke-RestMethod (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
Microsoft Identity Platform – Client Credentials Flow
Business Central API Reference
Join the Conversation
Share your thoughts, ask questions, or discuss this article with the community. All comments are moderated to ensure quality discussions.
No comments yet
Be the first to start the conversation!
0 Comments
Leave a Comment