Reputation: 453
I'm developing a Sharepoint Web Part that I want to use in Teams. I would like to obtain an access_token from the user logged in Teams using Adal library, without need to relogin.
I had tried something like this, but not works.
//ADAL.js configuration
let config = {
clientId: "XXXXXXXXXXX",
popUp: true
extraQueryParameters: "scope=openid+profile&login_hint=" + this.context.sdks.microsoftTeams.context.loginHint
};
let authContext = new AuthenticationContext(config);
authContext.login();
// See if there's a cached user and it matches the expected user
let user = authContext.getCachedUser();
if (user) {
if (user.userName !== this.context.sdks.microsoftTeams.context.loginHint) {
// User doesn't match, clear the cache
authContext.clearCache();
}
}
// Get the id token (which is the access token for resource = clientId)
let token = authContext.getCachedToken(config.clientId);
if (token) {
console.log(token);
} else {
// No token, or token is expired
authContext._renewIdToken((err, idToken) => {
if (err) {
console.log("Renewal failed: " + err);
// Failed to get the token silently; show the login button
} else {
console.log(idToken);
}
});
}
Have somebody any idea?
Regards
Upvotes: 1
Views: 239
Reputation: 453
Finally, I have found a solution that works in Sharepoint and Teams at the same time:
let loginName = this.context.pageContext.user.loginName;
let source = Sources.sharepoint;
// Obtaining loginName from Teams context
if (this.context.sdks.microsoftTeams) {
loginName = this.context.sdks.microsoftTeams.context.loginHint;
source = Sources.teams;
}
// Obtaining token provider
let tp = await this.context.aadTokenProviderFactory.getTokenProvider();
let config = tp["_defaultConfiguration"];
let aadInstanceUrl = config.aadInstanceUrl[length - 1] === "/" ? config.aadInstanceUrl : config.aadInstanceUrl + "/";
// Config context
let ctx = new AuthenticationContext({
tenant: tenantId,
clientId: clientId,
instance: aadInstanceUrl,
redirectUri: config.redirectUri,
extraQueryParameter: "login_hint=" + encodeURIComponent(loginName),
loadFrameTimeout: 60000
});
// Check user
let cu = ctx.getCachedUser();
console.log("USER", cu, loginName, ctx);
if (cu && cu.userName.toLowerCase() !== loginName.toLowerCase()) {
console.log("Clean user cache");
ctx.clearCache();
}
// Obtaining token using Adal library
let token = this.acquireToken(ctx, clientId);
// Render application
token.then((result) => {
console.log("iframe token: "+result); // "Stuff worked!"
}, (err) => {
console.log(err);
});
private acquireToken(ctx: AuthenticationContext, resource: string){
return new Promise((resolve, reject) => {
ctx.acquireToken(resource, (message, token) =>{
if(!token){
console.log("acquireToken: Error obtaining token: "+message);
reject(token);
}else{
console.log("acquireToken: Token: "+message);
resolve(token);
}
});
});
}
Upvotes: 1