401 未经授权使用 MSAL React 应用程序身份验证访问端点

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

我正在按照本教程使用 MSAL 对 React 应用程序进行身份验证,并使用身份验证令牌调用我自己的 api:https://github.com/oizhaolei/typescript-msal-sample

我添加了以下代码来进行 api 调用:

import { loginRequest, config } from "../authConfig";
import { msalInstance } from "../index";

export async function callMsGraph() {
    const account = msalInstance.getActiveAccount();
    if (!account) {
        throw Error("No active account! Verify a user has been signed in and setActiveAccount has been called.");
    }

    const response = await msalInstance.acquireTokenSilent({
        ...loginRequest,
        account: account
    });

    const headers = new Headers();
    const bearer = `Bearer ${response.accessToken}`;
    
    headers.append("Authorization", bearer);

    const options = {
        method: "GET",
        headers: headers
    };

    return fetch(config.endpoint, options)
        .then(response => response.json())        
        .catch(error => console.log(error));
}

authConfig.ts

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

// Config object to be passed to Msal on creation
export const msalConfig: Configuration = {
    auth: {
        clientId: "<client-id>",
        authority: "https://login.microsoftonline.com/<tenant-id>",
        redirectUri: "http://localhost:3000/",
        postLogoutRedirectUri: "/"
    }
};

// scopes
export const loginRequest = {
    scopes: ["api://<client-id>/user_impersonation"]
};

// endpoints 
export const config = {
    endpoint: "https://xxx-webapi.azurewebsites.net/api/v1/jobs"
};

运行时,我看到 401 未授权错误。我错过了什么?

reactjs typescript authentication msal msal-react
© www.soinside.com 2019 - 2024. All rights reserved.