我正在重新访问一个旧的项目,我最后一次更新是在大约1.5年前(此时它没有错误)。
从记忆中,我相信我当时使用这个教程来创建应用程序的基本基础。
加载应用程序现在我得到这个错误在Chrome开发工具:
Uncaught TypeError: MicrosoftGraph。MSALAuthenticationProviderOptions不是构造函数
在graph.js:1
graph.js
第1行代码为:
const authProviderOptions = new MicrosoftGraph.MSALAuthenticationProviderOptions(scopes);
用谷歌搜索上面的错误,似乎无法找到相关的结果。
以下是我认为与排除错误相关的应用程序的各个部分。
作为参考,它似乎我正在使用的MSAL版本需要从这个(https://alcdn.msauth.net/lib/1.3.0/js/msal.js
)"升级"到这个(https://alcdn.msauth.net/browser/2.18.0/js/msal-browser.min.js
),但是我还没有尝试过,以防它导致额外的问题,我还不知道如何解决。
index . html
<!-- msal -->
<!-- from: https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core -->
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.3.0/js/msal.js" integrity="sha384-xeOjp8/l8VazdeNFRbrC9LWPR1InyrS8E1Na/0lv6V2r09iwX6vJC47FXlczokMi" crossorigin="anonymous"></script>
<!-- javascript sdk -->
<!-- from: https://github.com/microsoftgraph/msgraph-sdk-javascript -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client/lib/graph-js-sdk.js"></script>
<!-- the logic of the app's functionality proceeds in the order below -->
<!-- set up click handlers etc -->
<script type="text/javascript" src="js/ui.js"></script>
<!-- define the configuration for msal -->
<script type="text/javascript" src="js/config.js"></script>
<!-- define authentication logic -->
<script type="text/javascript" src="js/auth.js"></script>
<!-- set up graph client and make api requests -->
<script type="text/javascript" src="js/graph.js"></script>
</body>
config.js
// check if running locally and set redirect uri accordingly
var hostname = location.hostname;
if (hostname === "localhost" || hostname === "127.0.0.1") {
console.log("running on localhost");
var redirect_uri = "http://localhost:8080";
}
else {
console.log("not running on localhost");
var redirect_uri = "https://somedomain.com";
}
// msal options
const msalConfig = {
auth: {
// this is the client/application id visible at:
// https://aad.portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps
clientId: "*******",
// this is the directory/tenant id visible at:
// https://aad.portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/client-id-is-here/isMSAApp/
redirectUri: redirect_uri,
authority: "https://login.microsoftonline.com/*******"
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false,
forceRefresh: false
}
// ,
// system: {
// logger: new Msal.Logger(
// loggerCallback ,{
// level: Msal.LogLevel.Verbose,
// piiLoggingEnabled: false,
// correlationId: '1234'
// }
// )
// }
};
// define application permissions
const scopes = ['directory.accessasuser.all', 'directory.readwrite.all', 'group.readwrite.all', 'groupmember.readwrite.all', 'openid', 'profile', 'sites.read.all', 'user.read', 'tasks.readwrite' ];
function loggerCallback(logLevel, message, containsPii) {
console.log(message);
}
auth.js
const msalApplication = new Msal.UserAgentApplication(msalConfig);
if (msalApplication.getAccount()) {
console.log("you refreshed the page and you are still signed in");
toggle_sign_in_and_sign_out();
}
const loginRequest = {
scopes: scopes
}
async function sign_in() {
try {
await msalApplication.loginPopup(loginRequest);
console.log('id_token acquired at: ' + new Date().toString());
var account_info = msalApplication.getAccount();
if (account_info) {
console.log("sign in success");
console.log(account_info);
show_response("n/a",account_info);
toggle_sign_in_and_sign_out();
}
} catch (error) {
console.log("sign in error");
console.log(error);
}
}
function sign_out() {
msalApplication.logout();
toggle_sign_in_and_sign_out();
}
graph.js
const authProviderOptions = new MicrosoftGraph.MSALAuthenticationProviderOptions(scopes);
const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalApplication, authProviderOptions);
const client_options = {
authProvider
};
const client = MicrosoftGraph.Client.initWithMiddleware(client_options);
async function get_stuff(endpoint) {
try {
if (endpoint === "my_details") {
var path = "/me";
var response = await client.api(path)
.get();
}
// there are different handlers here for different api requests
console.log(response);
} catch (error) {
throw error;
}
}
我需要做的修改如下:
(我有一个剩余的问题,当我重新加载页面时,图形请求不起作用,错误是:TypeError: Cannot read properties of undefined (reading 'api')
-也许我需要在页面加载时再次调用initializeGraphClient()
,以便graphClient
不是undefined
?…)
index . html
更改对MSAL和SDK脚本的引用:
<script src="https://alcdn.msauth.net/browser/2.16.1/js/msal-browser.min.js" integrity="sha384-bPBovDNeUf0pJstTMwF5tqVhjDS5DZPtI1qFzQI9ooDIAnK8ZCYox9HowDsKvz4i" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client@3.0.0/lib/graph-js-sdk.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client@3.0.0/lib/graph-client-msalBrowserAuthProvider.js"></script>
config.js
添加mailboxsettings.read
作用域,以便在graph.js
中定义的新getUser()
函数可以工作。
const scopes = ['directory.accessasuser.all', 'directory.readwrite.all', 'group.readwrite.all', 'groupmember.readwrite.all', 'mailboxsettings.read', 'openid', 'profile', 'sites.read.all', 'tasks.readwrite', 'user.read' ];
auth.js
多个变化-这是新的内容:
const msalInstance = new msal.PublicClientApplication(msalConfig);
if (sessionStorage.getItem("graphUser") !== null) {
console.log("you refreshed the page and you are still signed in");
toggle_sign_in_and_sign_out();
}
const loginRequest = {
scopes: scopes
}
async function sign_in() {
try {
// use MSAL to login
const authResult = await msalInstance.loginPopup(loginRequest);
console.log('id_token acquired at: ' + new Date().toString());
// initialize the graph client
initializeGraphClient(msalInstance, authResult.account, loginRequest.scopes);
// get the user's profile from Graph
var user = await getUser();
// save the profile in session
sessionStorage.setItem('graphUser', JSON.stringify(user));
toggle_sign_in_and_sign_out();
} catch (error) {
console.log(error);
}
}
function sign_out() {
sessionStorage.removeItem('graphUser');
msalInstance.logout();
toggle_sign_in_and_sign_out();
}
graph.js
多个变化-这里是新的内容:
let graphClient = undefined;
function initializeGraphClient(msalInstance, account, scopes)
{
// create an authentication provider
const authProvider = new MSGraphAuthCodeMSALBrowserAuthProvider
.AuthCodeMSALBrowserAuthenticationProvider(msalInstance, {
account: account,
scopes: scopes,
interactionType: msal.InteractionType.PopUp
});
// initialize the Graph client
graphClient = MicrosoftGraph.Client.initWithMiddleware({authProvider});
}
console.log("graphClient:");
console.log(graphClient);
async function getUser() {
return await graphClient
.api('/me')
// only get the fields used by the app
.select('id,displayName,mail,userPrincipalName,mailboxSettings')
.get();
}
async function get_stuff(endpoint) {
console.log("endpoint is: " + endpoint);
try {
if (endpoint === "my_details") {
var path = "/me";
var response = await graphClient.api(path)
.get();
}
// there are different handlers here for different api requests
console.log(response);
} catch (error) {
throw error;
}
}
引用
从MSAL 1迁移。
请注意,有很多关于身份验证主题的文档(以及可以完成的不同方法),我发现它很容易迷失。
JavaScript SDK将一些手动步骤"自动化",但是我必须非常仔细地阅读教程代码和MSAL文档,以查看它们是如何组合在一起的。