As per below code I am able to successfully log in and obtain an access token. However, when I make a request to the https://login.microsoftonline.com/{tenant-id}/openid/userinfo
API at runtime, I encounter a CORS error.
My code is as follows:
import React, { useEffect, useState } from 'react';
import { OidcClient } from 'oidc-client';
const LoginButton = () => {
const [user, setUser] = useState(null);
const handleLogin = async () => {
const config = {
authority: 'https://login.microsoftonline.com/{tenant-id}',
client_id: '{app-id}',
redirect_uri: 'http://localhost:3000',
response_type: 'code',
scope: 'openid profile user.read',
};
const userManager = new OidcClient(config);
const state = { nonce: generateNonce() };
const request = await userManager.createSigninRequest({ state });
saveState(state); // Persist the state to storage
window.location.href = request.url;
};
useEffect(() => {
const processCallback = async () => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const savedState = getState(); // Retrieve the state from storage
if (code && savedState) {
const config = {
authority: 'https://login.microsoftonline.com/{tenant-id}',
client_id: '{app-id}',
redirect_uri: "http://localhost:3000",
response_type: 'code',
scope: 'openid profile',
};
const userManager = new OidcClient(config);
const response = await userManager.processSigninResponse();
const userProfile = await userManager.getUser();
setUser(userProfile);
clearState(); // Clear the state from storage after successful authentication
}
};
processCallback();
}, []);
const generateNonce = () => {
// Implement your nonce generation logic here
// For example, you can use a random string generator library
return 'generated-nonce';
};
const saveState = (state) => {
localStorage.setItem('authState', JSON.stringify(state));
};
const getState = () => {
const savedState = localStorage.getItem('authState');
return savedState ? JSON.parse(savedState) : null;
};
const clearState = () => {
localStorage.removeItem('authState');
};
return (
<div>
{user && user.profile ? (
<>
<p>Welcome, {user.profile.given_name}!</p>
<p>Access Token: {user.access_token}</p>
</>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
};
export default LoginButton;
What's wrong in the above code or I did mistake in AzureAD app. why CORS error occurring, I did any mistake in code want to understand what is my mistake. Also attached the screenshot for reference.