0

Due to work moving from Google Suite to Microsoft have started to learn the basics of Typescript. Previously reached an on-par grade with VBA. After reading several forums, I wondered if anyone knew how to simply get the user's name or email address that is using an online Excel sheet? Previously the VBA code was simply:

dim username as string
username = Application.Username

Then this variable could set a value in A1.

Any suggestions warmly received.

Best wishes,

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45

1 Answers1

2

The Office JavaScript API doesn't provide any property or method for that out of the box. But you may consider retrieving the required information from the access token (JWT) which is used in case of SSO, check out 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.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • Thank you for this answer and will feedback. All the best David – David Howarth Jan 30 '23 at 15:51
  • I'm getting the error 'See line 32, column 9: Office Scripts cannot infer the data type of this variable. Please declare a type for the variable'. That is the "getAccessToken()" function call line. Being a typescript noob, am I suppose to add the jwt-decode library somewhere? – ExcelEverything Jul 05 '23 at 11:03