AudienceUriValidationFailedException SharePoint token error

You might get an error of type AudienceUriValidationFailedException when you are trying to access a SharePoint APIs securely using Microsoft Identity platform Azure AD OAuth2 authorization flow. In my case, I was trying to get an access token using a refresh token and use it with the SharePoint APIs from Postman. However, I got the following error.

401 Unauthorized and Response: {"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}

Pasting my token in showed that the encoded value of the 'aud' attribute is wrong indeed since I was trying to access my app itself as a resource instead of SharePoint online. The right solution was to replace the resource in the payload sent to get the access token, so the resource will become the SharePoint site domain like Here is how this might look when creating the payload:

const requestBody: any = {
grant_type: 'refresh_token',
client_id: '<YOUR_APP_CLIENT_ID>',
refresh_token: '<YOUR_REFRESH_TOKEN>',
resource: '',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'

request('', {
headers: {
'Accept': 'application/json'
method: 'POST',
formData: requestBody
}, (err: any, response: any, body: any) => {