Azure React WebApp 显示 PKCE 问题

问题描述 投票:0回答:1

获取PKCE(跨域授权码兑换需要兑换码证明密钥)

enter image description here

我已经在Azure WebApp上部署了react webApp,该平台有SPA 我也添加了重定向网址

这是文件

这是index.js文件

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

这是 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);

这是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;

在App中注册 enter image description here

当我在App注册中将平台从SPA切换到Web时 应用程序将打开,但仍然不存在包含用户信息的令牌生成 如何解决这个问题。

我应该采取什么步骤来解决 pkce 问题,并且 sessionStorage 用户数据应该可见,

javascript azure azure-ad-msal msal.js azure-app-registration
1个回答
0
投票

我使用了你的代码,只是更改了

client id
authority
redirecturi
,它对我来说工作得很好。

  • 确保如果您的 SPA 向不同域(跨源)发出请求,请确保托管 API 或后端资源的服务器具有适当的 CORS(跨源资源共享)设置,配置为允许来自 SPA 域的请求。

  • 确保您拥有服务主体所需的访问权限和同意。

  • 浏览器隐私设置或扩展程序可能会干扰跨源请求,包括授权代码流所需的请求。禁用任何可能阻止这些请求的浏览器扩展或隐私设置。

OUTPUT

© www.soinside.com 2019 - 2024. All rights reserved.