Reputation: 33
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,
Upvotes: 0
Views: 1480
Reputation: 49397
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.
Upvotes: 2