Generate Access Token via Service Principal

Nandan Hegde
27,241
Reputation points MVP
Currently we are generating an Access Token within Azure automation via Managed Identity based on the below code:
$bearer_token = (Invoke-RestMethod -Method Get -Headers @{"X-IDENTITY-HEADER"="$env:IDENTITY_HEADER"} -Uri "$( $env:IDENTITY_ENDPOINT )?resource=499b84ac-1321-427f-aa17-267ca6975798&api-version=2019-08-01").access_token
$bearer_token
Now the devops/offering is moving to a different tenant because of which we cannot use Managed Identity and we need to switch to Service principal way.
So can anyone suggest how to generate the access token based on the above configuration and leveraging an app