I have an application with a NodeJS backend and a React frontend, and I want to implement Azure SSO for it. Since the frontend is served by the backend, users who want to log in to the application are redirected by the backend to the login page on the frontend. When users click on the relevant button on the login page, the Azure authentication page should open, and after login, they should be redirected back to my application. However, I am getting an error on the API side as shown below.
Access to XMLHttpRequest at 'https://login.microsoftonline.com/xxx/oauth2/v2.0/authorize?client_id={clientid}1&response_type=code&redirect_uri=http:%2F%2Flocalhost:3000%2Fauth%2Fcallback&response_mode=query&scope=https:%2F%2Fgraph.microsoft.com%2F.default+offline_access' (redirected from 'http://localhost:3000/api/auth/sso-login') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my api code is
const params = new URLSearchParams({
client_id: CLIENT_ID,
response_type: 'code',
redirect_uri: REDIRECT_URI,
response_mode: 'query',
scope: 'https://graph.microsoft.com/.default offline_access'
});
res.redirect(`${authorizeUrl}?${params.toString()}`);
i created a simple nodejs app with same logic without frontend, it worked without problem.
app.get('/login', (req, res) => {
const params = new URLSearchParams({
client_id: CLIENT_ID,
response_type: 'code',
redirect_uri: REDIRECT_URI,
response_mode: 'query',
scope: 'https://graph.microsoft.com/.default offline_access'
});
res.redirect(`${authorizeUrl}?${params.toString()}`);
});
app.get('/auth/callback', async (req, res) => {
const { code } = req.query;
if (!code) {
return res.status(400).send('Authorization code not found.');
}
try {
const response = await axios.post(tokenUrl, new URLSearchParams({
client_id: CLIENT_ID,
scope: 'https://graph.microsoft.com/.default',
code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
client_secret: CLIENT_SECRET
}));
const accessToken = response.data.access_token;
res.send(`Access Token: ${accessToken}`);
} catch (error) {
res.status(500).send(`Error exchanging code: ${error.message}`);
}
});```







