skip to Main Content

Getting issue PKCE(Proof Key for Code Exchange is required for cross-origin authorization code redemption.)

enter image description here

I have react webApp deployed on Azure WebApp , the platform there is SPA
I added the redirect URL as well

Here are the file

This is index.js File

type himport React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { PublicClientApplication, EventType } from "@azure/msal-browser";
import { msalConfig } from "./auth-config";

// Create MSAL instance
const msalInstance = new PublicClientApplication(msalConfig);

// Checking for access token acquisition
msalInstance.addEventCallback((event) => {
  if (
    event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS &&
    event.payload.accessToken
  ) {
    console.log("Access token acquired:", event.payload.accessToken);
  }
  if (event.eventType === EventType.ACQUIRE_TOKEN_FAILURE) {
    console.error("Failed to acquire access token:", event.error);
  }
});

// Set active account if not already set
if (
  !msalInstance.getActiveAccount() &&
  msalInstance.getAllAccounts().length > 0
) {
  console.log("Setting active account", msalInstance.getAllAccounts()[0]);
  msalInstance.setActiveAccount(msalInstance.getAllAccounts()[0]);
}

// Add event callback to update active account on successful login or token acquisition
msalInstance.addEventCallback((event) => {
  if (
    (event.eventType === EventType.LOGIN_SUCCESS ||
      event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS ||
      event.eventType === EventType.SSO_SILENT_SUCCESS) &&
    event.payload.account
  ) {
    msalInstance.setActiveAccount(event.payload.account);
  }

  console.log("MSAL Event:", event); // Log MSAL event
});

// Create root element and render App component
const root = ReactDOM.createRoot(document.getElementById("root"));
console.log("MSAL Instance:", msalInstance); // Log MSAL instance
root.render(<App instance={msalInstance} />);
ere

This is auth-config.js

import { LogLevel } from "@azure/msal-browser";

export const msalConfig = {
  auth: {
    // This is the only mandatory field that you need to supply.
    clientId: "{ClientId}",
    authority: "https://login.microsoftonline.com/{tennatId}",
    redirectUri:"https://webAapp.azurewebsites.net/.auth/login/aad/callback",
    postLogoutRedirectUri: "/",
    navigateToLoginRequestUrl: false,
    validateAuthority: true,
  },
  cache: {
    cacheLocation: "sessionStorage",
    storeAuthStateInCookie: false,
  },
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        console.log("MSAL Logging:", level, message); // Log all MSAL messages
        if (containsPii) {
          return;
        }
        switch (level) {
          case LogLevel.Error:
            console.error(message);
            return;
          case LogLevel.Info:
            console.info(message);
            return;
          case LogLevel.Verbose:
            console.debug(message);
            return;
          case LogLevel.Warning:
            console.warn(message);
            return;
          default:
            return;
        }
      },
    },
  },
};

export const loginRequest = {
  scopes: ["user.read"],
};

// Additional logging for clarity
console.log("MSAL Configuration:", msalConfig);
console.log("Login Request:", loginRequest);

this is the App.js

import "./App.css";

import {
  AuthenticatedTemplate,
  UnauthenticatedTemplate,
  useMsal,
  MsalProvider,
} from "@azure/msal-react";
import { loginRequest } from "./auth-config";

const WrappedView = () => {
  const { instance } = useMsal();
  const activeAccount = instance.getActiveAccount();
  console.log("Active Account:", activeAccount); // Log the active account
  console.log("Login Request:", loginRequest); // Log the login request
  const handleRedirect = () => {
    instance
      .loginRedirect({
        ...loginRequest,
        prompt: "create",
      })
      .catch((error) => console.error(error));
  };

  return (
    <div className="App">
      <AuthenticatedTemplate>
        {activeAccount ? <p>Authenticated successfully</p> : null}
      </AuthenticatedTemplate>
      <UnauthenticatedTemplate>
        <button onClick={handleRedirect}>Sign up</button>
      </UnauthenticatedTemplate>
    </div>
  );
};

const App = ({ instance }) => {
  console.log("Msal Instance:", instance); // Log the MSAL instance
  return (
    <MsalProvider instance={instance}>
      <WrappedView />
    </MsalProvider>
  );
};

export default App;

In the App registration
enter image description here

When i switch the platform from SPA to web in the App registration
App will open but still the token generation in which contain user information is not there
How to fix this.

What step should i follow that pkce issue should resolved and and sessionStorage the user data should be visible,

2

Answers


  1. Chosen as BEST ANSWER

    I got the answer. we need to add 2 platforms in the App Registration of the WebApp.

    1. Add Web where the redirect link will be the callback authentication link ex. https://webApp.azurewebsite.net/.auth/add/callback
    2. Add SPA where the link should be website link. ex: https://webApp.azurewebsite.net/

    Enable both in Implicit grant type i.e access token and id token

    Note: i added localhost as well in the SPA platform as i will be using this for local development as well.

    enter image description here


  2. I used your code and just changed client id , authority and redirecturi, its working fine for me.

    • Make sure If your SPA makes requests to a different domain (cross-origin), ensure that the server hosting your API or backend resources has appropriate CORS (Cross-Origin Resource Sharing) settings configured to allow requests from your SPA’s domain.

    • Make sure You have required access and consent in the service principal.

    • Browser privacy settings or extensions may interfere with cross-origin requests, including those required for the authorization code flow. Disable any browser extensions or privacy settings that might be blocking these requests.

    OUTPUT:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search