user3881465
user3881465

Reputation: 269

How to get user info using Office-js-helper's Authentication?

I am working on Excel Web Add-In. I am using OfficeDev/office-js-helpers library for authenticating user. Following code is working fine. But I don't know how to get user's email, user name etc.

Is there any function available in OfficeDev/office-js-helpers through which I can get user info ?

if (OfficeHelpers.Authenticator.isAuthDialog()) {
  return;
}

var authenticator = new OfficeHelpers.Authenticator();

// register Microsoft (Azure AD 2.0 Converged auth) endpoint using
authenticator.endpoints.registerMicrosoftAuth('clientID');

// for the default Microsoft endpoint
authenticator
    .authenticate(OfficeHelpers.DefaultEndpoints.Microsoft)
    .then(function (token) { 
    /* My code after authentication and here I need user's info */ })
    .catch(OfficeHelpers.Utilities.log);

Code sample will be much helpful.

Upvotes: 3

Views: 1327

Answers (2)

blandine
blandine

Reputation: 93

Once you have the Microsoft token, you can send a request to https://graph.microsoft.com/v1.0/me/ to get user information. This request must have an authorization header containing the token you got previously.

Here is an example using axios :

const config = { 'Authorization': `Bearer ${token.access_token}` };
axios.get(`https://graph.microsoft.com/v1.0/me/`, {
    headers: config
}).then((data)=> {
    console.log(data); // data contains user information
};

Upvotes: 2

Marc LaFleur
Marc LaFleur

Reputation: 33094

This code only provides you the token for the user. In order to obtain information about the user, you'll need to make calls into Microsoft Graph API. You can find a full set of documentation on that site.

If you're only authenticating in order to get profile information, I'd recommend looking at Enable single sign-on for Office Add-ins (preview). This is a much cleaner method of obtaining an access token for a user. It is still in preview at the moment so it's feasibility will depend on where you're planning to deploy your add-in.

Upvotes: 4

Related Questions