Prithavi raj
Prithavi raj

Reputation: 11

How to get user mail id and user name from Office.js or Office API

I am working on Word , Excel and PowerPoint add-ins . I want to upload document from graphs API .Below are API PUT https://graph.microsoft.com/v1.0/users/**[email protected]**/drive/items/root:/filename.docx:/content and it is working fine from Postman .

My concern how I will get USER Mail Id from Word , Excel and PowerPoint add-ins as Any direct API not available .

I follow below article still not success and getting 13006 error .

message: "An unexpected error occurred in the client." name: "Error occurred in the authentication request from Office."

https://learn.microsoft.com/en-us/office/dev/add-ins/develop/register-sso-add-in-aad-v2

https://learn.microsoft.com/en-us/office/dev/add-ins/develop/sso-in-office-add-ins#register-your-add-in-with-the-microsoft-identity-platform

 async  getToken() { 
    var returnObject; 
    window.Office.context.auth.getAccessTokenAsync({ allowConsentPrompt: true, allowSignInPrompt: true },function (result) { 
      console.log( result); 

      if (result.status === "succeeded") {
         var token = result.value; 
         returnObject = token; 
         console.log(token)
        } else { 
          console.log("Error obtaining token", result); 
        }
         });
          return returnObject; 
   }

Upvotes: 0

Views: 1427

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49455

You can use the following code:

async function getUserData() {
    try {
        let userTokenEncoded = await OfficeRuntime.auth.getAccessToken();
        let userToken = jwt_decode(userTokenEncoded); // Using the https://www.npmjs.com/package/jwt-decode library.
        console.log(userToken.name); // user name
        console.log(userToken.preferred_username); // email
        console.log(userToken.oid); // user id     
    }
    catch (exception) {
        if (exception.code === 13003) {
            // SSO is not supported for domain user accounts, only
            // Microsoft 365 Education or work account, or a Microsoft account.
        } else {
            // Handle error
        }
    }
}

If your add-in is loaded on an older version of Office that does not support SSO, the getAccessToken call will fail. For Excel, Word, and PowerPoint add-ins you will typically want to fall back to using the Microsoft identity platform. For more information, see Authenticate with the Microsoft identity platform.

See Enable single sign-on (SSO) in an Office Add-in for more information.

Upvotes: 0

Related Questions