如何在Sharepoint Web部件内使用MSAL库获取accessToken



我开发了一个Sharepoint Web部件,需要在其中获取accessToken。为了获得令牌,我使用了MSAL库。

我的问题是下一个:我登录了我的Sharepoint,但当Web部件尝试检索accessToken时,身份验证失败,出现以下错误:

xxxx web part.js:1838 ClientAuthError:需要用户登录。在ClientAuthError.AuthError[作为构造函数](https://localhost:4321/dist/xxx-web部件.js:2057:28(在新的ClientAuthError(https://localhost:4321/dist/xxxx-web部件.js:630:28(在函数.7ZR7.ClientAuthError.createUserLoginRequiredError(https://localhost:4321/dist/xxxx-网页部分js:682:16(在https://localhost:4321/dist/xxx-web部件js:2916:103在new Promise((在UserAgentApplication.ZES5.UserAgentApplication.acquireTokenSilent(https://localhost:4321/dist/xxxx-网页部分js:2905:16(在UserAgentApplication.descriptor.value[作为acquireTokenSilent](https://localhost:4321/dist/xxxx-网页部分js:2543:38(位于xxxWebPart.PlTk.xxxxWebPart.render(https://localhost:4321/dist/xxxx-网页部分js:11828:19(位于xxxxWebPart.t_renderWithAccessibleTitle(https://spoprod-a.akamaihd.net/files/sp-client/sp-webpart-workbench-assembly_en-us_27e01b6941bf5cdddecc695bd3bdbb95.js:21:585834)在https://spoprod-a.akamaihd.net/files/sp-client/sp-webpart-workbench-assembly_en-us_27e01b6941bf5cdddecc695bd3bdbb95.js:21:585352

如何解决这个问题?。如果我登录Sharepoint,我希望在不重新登录系统的情况下获得accessToken。

这是我的代码:

export default class MyWebPart extends BaseClientSideWebPart <IWebpartProps> {
public render(): void {
const config = {
auth: {
clientId: "xxxxxxxxxxxxxxx",
authority: "https://login.microsoftonline.com/yyyyyyyyyyyyyyyyyyy"
}
};
const myMSALObj = new UserAgentApplication(config);
let accessTokenRequest = {
scopes: ["user.read"]
}
myMSALObj.acquireTokenSilent(accessTokenRequest).then(function(accessTokenResponse) {
// Acquire token silent success
// call API with token
let accessToken = accessTokenResponse.accessToken;
let scopes = accessTokenResponse.scopes;
}).catch(function (error) {
//Acquire token silent failure, and send an interactive request
console.log(error);
if (error.errorMessage.indexOf("interaction_required") !== -1) {
myMSALObj.acquireTokenRedirect(accessTokenRequest);
}
});

最后,我找到了一个类似的解决方法:

var accessTokenRequest = {
scopes: ["user.read"],
loginHint: preferred_username,
extraQueryParameters: {domain_hint: 'organizations'}
}

祝福与晚安

最新更新