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.
Before we jump in, make sure you've got:
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.
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()); }
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`;
Time to send your user on a little journey:
window.location.href = authUrl;
They're back! Let's grab that auth code:
const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get('code');
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();
Keep those tokens safe! Consider using the browser's sessionStorage or a secure cookie.
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(); }
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}` } })
Remember:
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!
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!
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!