Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get Office 365 Groups and Current User Profile using the Graph API and AdalJS to acquire access tokens
console.clear();
/* Logging levels
0: Error
1: Warning
2: Info
3: Verbose
*/
(function() {
/* LOAD ADAL.JS onto the page
see: https://github.com/AzureAD/azure-activedirectory-library-for-js/wiki/Installation
*/
return new Promise( (resolve,reject) => {
s = document.createElement("script");
s.src = "https://secure.aadcdn.microsoftonline-p.com/lib/1.0.17/js/adal.min.js"
s.onload = function() {
console.log(">> Loaded: adal.min.js");
resolve();
}
document.getElementsByTagName("head")[0].append(s);
});
}
)().then( async () => {
/* Use ADAL to perform a Silent Login and get an AccessToken */
console.log(">>> AdalJS is loaded, can start working...");
/* see: https://github.com/AzureAD/azure-activedirectory-library-for-js/wiki/Config-authentication-context */
const clientId = _spPageContextInfo.spfx3rdPartyServicePrincipalId;
const authContext = new AuthenticationContext({
clientId: clientId,
tenant: _spPageContextInfo.aadTenantId,
redirectUri: window.location.origin + '/_forms/spfxsinglesignon.aspx',
cacheLocation: 'sessionStorage' // Other option is localStorage
});
/* if ADAL logging is required, uncomment the lines below... */
/*window.Logging = {
level: 3,
log: function (message) {
console.log(message);
},
piiLoggingEnabled: true
};*/
/* to clear the ADAL local/session cache... */
// authContext.clearCache();
function silentLoginWithAccessToken() {
return new Promise( (resolve, reject) => {
console.info("Performing silenLogin()...");
authContext._renewToken(clientId, (errorMsg, token) => {
if (!token || errorMsg) {
const err = new Error(errorMsg || "No Token and No Error Msg");
console.error("silentLoginWithAccessToken() error:", err);
reject(err);
} else {
const user = authContext.getCachedUser();
resolve({ token, user });
}
}, authContext.RESPONSE_TYPE.ID_TOKEN_TOKEN);
});
}
function getTokenForResource(resource) {
return new Promise( (resolve, reject) => {
console.info(`>>> Getting Token for ${resource} ...`);
authContext.acquireToken(resource, (errorMsg, token) => {
if (!token || errorMsg) {
const err = new Error(errorMsg || "No Token and No Error Msg");
console.error(`getTokenForResource(${resource}) error:`, err);
reject(err);
} else {
resolve(token);
}
});
});
}
function getGroups(accessToken) {
return new Promise( async (resolve, reject) => {
console.info(">>> Getting Office 365 Groups...");
const url = `https://graph.microsoft.com/v1.0/groups`;
const response = await fetch(url, {
"method": "GET",
"headers": {
"Accept": "application/json",
"Authorization": `Bearer ${accessToken}`,
},
});
const data = await response.json();
console.info(data);
resolve(data);
});
}
function getMyProfile(accessToken) {
return new Promise( async (resolve, reject) => {
console.info(">> Getting MyProfile...");
const url = `https://graph.microsoft.com/v1.0/me`;
const response = await fetch(url, {
"method": "GET",
"headers": {
"Accept": "application/json",
"Authorization": `Bearer ${accessToken}`,
},
});
const data = await response.json();
console.info(data);
resolve(data);
});
}
try {
const authData = await silentLoginWithAccessToken();
console.info("authData", authData);
/* this access token is a user+id access token to the "SharePoint Online Client Extensibility Web Application Principal"
app registration itself and cannot be used to access data from other APIs
it can be used to exchange for an access token to another API though
*/
console.info(`accessToken (${clientId})`, authData.token);
/* get an access token to the graph API */
const accessToken = await getTokenForResource("https://graph.microsoft.com");
console.info("accessToken (https://graph.microsoft.com)", accessToken);
const groups = await getGroups(accessToken);
console.info("office 365 groups", groups.value);
const profile = await getMyProfile(accessToken);
console.info("my profile", profile);
} catch (e) {
console.error("CATCH: ", e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.