Back

How to build a public Microsoft Dynamics 365 ERP integration: Building the Auth Flow

Aug 3, 20246 minute read

Hey there, fellow JavaScript devs! Ready to dive into the world of Microsoft Dynamics 365 ERP integration? Today, we're focusing on the crucial part of any integration: the auth flow. Let's get your users securely connected to Dynamics 365 without breaking a sweat.

Prerequisites

Before we jump in, make sure you've got:

  • An Azure AD app registration (you're a pro, so I'm sure you've got this covered)
  • The right permissions and scopes set up (you know, the usual suspects for Dynamics 365)

Auth Flow Overview

We're going with the OAuth 2.0 authorization code flow with PKCE. It's like the regular auth code flow, but with a dash of extra security. Perfect for public clients like our JavaScript app.

Implementing the Auth Flow

Generate PKCE code verifier and challenge

First things first, let's create our PKCE code verifier and challenge:

function generateCodeVerifier() { return base64URLEncode(crypto.randomBytes(32)); } function generateCodeChallenge(verifier) { return base64URLEncode(crypto.createHash('sha256').update(verifier).digest()); }

Construct the authorization URL

Now, let's build that authorization URL:

const authUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` + `client_id=${clientId}&` + `response_type=code&` + `redirect_uri=${encodeURIComponent(redirectUri)}&` + `scope=${encodeURIComponent(scope)}&` + `code_challenge=${codeChallenge}&` + `code_challenge_method=S256`;

Redirect user to Microsoft login page

Time to send your user on a little journey:

window.location.href = authUrl;

Handle the authorization code callback

They're back! Let's grab that auth code:

const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get('code');

Exchange authorization code for access token

Now for the good stuff - let's get that access token:

const tokenResponse = await fetch('https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token', { method: 'POST', body: new URLSearchParams({ client_id: clientId, scope: scope, code: code, redirect_uri: redirectUri, grant_type: 'authorization_code', code_verifier: codeVerifier }) }); const tokens = await tokenResponse.json();

Store and manage tokens securely

Keep those tokens safe! Consider using the browser's sessionStorage or a secure cookie.

Refreshing Access Tokens

Don't forget to refresh those tokens before they expire:

async function refreshAccessToken(refreshToken) { const response = await fetch('https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token', { method: 'POST', body: new URLSearchParams({ client_id: clientId, scope: scope, refresh_token: refreshToken, grant_type: 'refresh_token' }) }); return await response.json(); }

Making Authenticated Requests

Now you're ready to rock! Just include that access token in your API requests:

fetch('https://your-dynamics-365-url/api/data/v9.2/accounts', { headers: { 'Authorization': `Bearer ${accessToken}` } })

Security Considerations

Remember:

  • Always use HTTPS
  • Store tokens securely (no localStorage, please!)
  • Use state parameters to prevent CSRF attacks

Error Handling and Edge Cases

Keep an eye out for those pesky 401 errors - they might mean it's time to refresh your token. And don't forget to handle user cancellations gracefully!

Testing and Debugging

Pro tip: Use tools like Postman or the Azure AD auth playground to test your OAuth flow. And when in doubt, check those network requests!

Wrapping Up

And there you have it! You've just built a rock-solid auth flow for your Dynamics 365 ERP integration. Remember, security is key, so always stay on your toes and keep your code tight.

Next up: start pulling that sweet, sweet Dynamics 365 data into your app. Happy coding, and may your integrations always be smooth and your tokens ever-refreshing!