@microsoft/teamsfx 0.4.1-alpha.fcc60ca0.0 → 0.4.2-alpha.7b2fe9ea.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import jwt_decode from 'jwt-decode';
2
2
  import * as microsoftTeams from '@microsoft/teams-js';
3
- import axios from 'axios';
3
+ import { PublicClientApplication } from '@azure/msal-browser';
4
4
  import { Client } from '@microsoft/microsoft-graph-client';
5
5
 
6
6
  // Copyright (c) Microsoft Corporation.
@@ -309,6 +309,57 @@ function getUserInfoFromSsoToken(ssoToken) {
309
309
  }
310
310
  return userInfo;
311
311
  }
312
+ /**
313
+ * @internal
314
+ */
315
+ function getTenantIdAndLoginHintFromSsoToken(ssoToken) {
316
+ if (!ssoToken) {
317
+ const errorMsg = "SSO token is undefined.";
318
+ internalLogger.error(errorMsg);
319
+ throw new ErrorWithCode(errorMsg, ErrorCode.InvalidParameter);
320
+ }
321
+ const tokenObject = parseJwt(ssoToken);
322
+ const userInfo = {
323
+ tid: tokenObject.tid,
324
+ loginHint: tokenObject.ver === "2.0"
325
+ ? tokenObject.preferred_username
326
+ : tokenObject.upn,
327
+ };
328
+ return userInfo;
329
+ }
330
+ /**
331
+ * @internal
332
+ */
333
+ function parseAccessTokenFromAuthCodeTokenResponse(tokenResponse) {
334
+ try {
335
+ const tokenResponseObject = typeof tokenResponse == "string"
336
+ ? JSON.parse(tokenResponse)
337
+ : tokenResponse;
338
+ if (!tokenResponseObject || !tokenResponseObject.accessToken) {
339
+ const errorMsg = "Get empty access token from Auth Code token response.";
340
+ internalLogger.error(errorMsg);
341
+ throw new Error(errorMsg);
342
+ }
343
+ const token = tokenResponseObject.accessToken;
344
+ const tokenObject = parseJwt(token);
345
+ if (tokenObject.ver !== "1.0" && tokenObject.ver !== "2.0") {
346
+ const errorMsg = "SSO token is not valid with an unknown version: " + tokenObject.ver;
347
+ internalLogger.error(errorMsg);
348
+ throw new Error(errorMsg);
349
+ }
350
+ const accessToken = {
351
+ token: token,
352
+ expiresOnTimestamp: tokenObject.exp * 1000,
353
+ };
354
+ return accessToken;
355
+ }
356
+ catch (error) {
357
+ const errorMsg = "Parse access token failed from Auth Code token response in node env with error: " +
358
+ error.message;
359
+ internalLogger.error(errorMsg);
360
+ throw new ErrorWithCode(errorMsg, ErrorCode.InternalError);
361
+ }
362
+ }
312
363
  /**
313
364
  * Format string template with replacements
314
365
  *
@@ -548,43 +599,10 @@ class OnBehalfOfUserCredential {
548
599
  }
549
600
 
550
601
  // Copyright (c) Microsoft Corporation.
551
- // Licensed under the MIT license.
552
- /**
553
- * Configuration used in initialization.
554
- * @internal
555
- */
556
- class Cache {
557
- static get(key) {
558
- return sessionStorage.getItem(key);
559
- }
560
- static set(key, value) {
561
- sessionStorage.setItem(key, value);
562
- }
563
- static remove(key) {
564
- sessionStorage.removeItem(key);
565
- }
566
- }
567
-
568
- // Copyright (c) Microsoft Corporation.
569
- // Licensed under the MIT license.
570
- /**
571
- * @internal
572
- */
573
- var GrantType;
574
- (function (GrantType) {
575
- GrantType["authCode"] = "authorization_code";
576
- GrantType["ssoToken"] = "sso_token";
577
- })(GrantType || (GrantType = {}));
578
-
579
- // Copyright (c) Microsoft Corporation.
580
- const accessTokenCacheKeyPrefix = "accessToken";
581
- const separator = "-";
582
602
  const tokenRefreshTimeSpanInMillisecond = 5 * 60 * 1000;
583
603
  const initializeTeamsSdkTimeoutInMillisecond = 5000;
584
604
  const loginPageWidth = 600;
585
605
  const loginPageHeight = 535;
586
- const maxRetryCount = 3;
587
- const retryTimeSpanInMillisecond = 3000;
588
606
  /**
589
607
  * Represent Teams current user's identity, and it is used within Teams tab application.
590
608
  *
@@ -602,7 +620,6 @@ class TeamsUserCredential {
602
620
  * ```typescript
603
621
  * const config = {
604
622
  * authentication: {
605
- * runtimeConnectorEndpoint: "https://xxx.xxx.com",
606
623
  * initiateLoginEndpoint: "https://localhost:3000/auth-start.html",
607
624
  * clientId: "xxx"
608
625
  * }
@@ -620,6 +637,7 @@ class TeamsUserCredential {
620
637
  internalLogger.info("Create teams user credential");
621
638
  this.config = this.loadAndValidateConfig();
622
639
  this.ssoToken = null;
640
+ this.initialized = false;
623
641
  }
624
642
  /**
625
643
  * Popup login page to get user's access token with specific scopes.
@@ -637,7 +655,6 @@ class TeamsUserCredential {
637
655
  * @param scopes - The list of scopes for which the token will have access, before that, we will request user to consent.
638
656
  *
639
657
  * @throws {@link ErrorCode|InternalError} when failed to login with unknown error.
640
- * @throws {@link ErrorCode|ServiceError} when simple auth server failed to exchange access token.
641
658
  * @throws {@link ErrorCode|ConsentFailed} when user canceled or failed to consent.
642
659
  * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
643
660
  * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
@@ -648,27 +665,39 @@ class TeamsUserCredential {
648
665
  validateScopesType(scopes);
649
666
  const scopesStr = typeof scopes === "string" ? scopes : scopes.join(" ");
650
667
  internalLogger.info(`Popup login page to get user's access token with scopes: ${scopesStr}`);
668
+ if (!this.initialized) {
669
+ await this.init();
670
+ }
651
671
  return new Promise((resolve, reject) => {
652
672
  microsoftTeams.initialize(() => {
653
673
  microsoftTeams.authentication.authenticate({
654
- url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}`,
674
+ url: `${this.config.initiateLoginEndpoint}?clientId=${this.config.clientId}&scope=${encodeURI(scopesStr)}&loginHint=${this.loginHint}`,
655
675
  width: loginPageWidth,
656
676
  height: loginPageHeight,
657
677
  successCallback: async (result) => {
658
678
  if (!result) {
659
- const errorMsg = "Get empty authentication result from Teams";
679
+ const errorMsg = "Get empty authentication result from MSAL";
660
680
  internalLogger.error(errorMsg);
661
681
  reject(new ErrorWithCode(errorMsg, ErrorCode.InternalError));
662
682
  return;
663
683
  }
664
- const authCodeResult = JSON.parse(result);
684
+ let resultJson = {};
665
685
  try {
666
- await this.exchangeAccessTokenFromSimpleAuthServer(scopesStr, authCodeResult);
686
+ resultJson = JSON.parse(result);
687
+ }
688
+ catch (error) {
689
+ // If can not parse result as Json, will NOT throw error since user may return other info in auth-end page.
690
+ // TODO: resolve the result.
691
+ const failedToParseResult = "Failed to parse result to Json.";
692
+ internalLogger.verbose(failedToParseResult);
667
693
  resolve();
694
+ return;
668
695
  }
669
- catch (err) {
670
- reject(this.generateAuthServerError(err));
696
+ // If sessionStorage exists in result, set the values in current session storage.
697
+ if (resultJson.sessionStorage) {
698
+ this.setSessionStorage(resultJson.sessionStorage);
671
699
  }
700
+ resolve();
672
701
  },
673
702
  failureCallback: (reason) => {
674
703
  const errorMsg = `Consent failed for the scope ${scopesStr} with error: ${reason}`;
@@ -703,7 +732,6 @@ class TeamsUserCredential {
703
732
  *
704
733
  * @throws {@link ErrorCode|InternalError} when failed to get access token with unknown error.
705
734
  * @throws {@link ErrorCode|UiRequiredError} when need user consent to get access token.
706
- * @throws {@link ErrorCode|ServiceError} when failed to get access token from simple auth server.
707
735
  * @throws {@link ErrorCode|InvalidParameter} when scopes is not a valid string or string array.
708
736
  * @throws {@link ErrorCode|RuntimeNotSupported} when runtime is nodeJS.
709
737
  *
@@ -724,21 +752,47 @@ class TeamsUserCredential {
724
752
  }
725
753
  else {
726
754
  internalLogger.info("Get access token with scopes: " + scopeStr);
727
- const cachedKey = await this.getAccessTokenCacheKey(scopeStr);
728
- const cachedToken = this.getTokenCache(cachedKey);
729
- if (cachedToken) {
730
- if (!this.isAccessTokenNearExpired(cachedToken)) {
731
- internalLogger.verbose("Get access token from cache");
732
- return cachedToken;
755
+ if (!this.initialized) {
756
+ await this.init();
757
+ }
758
+ let tokenResponse;
759
+ const scopesArray = typeof scopes === "string" ? scopes.split(" ") : scopes;
760
+ const domain = window.location.origin;
761
+ // First try to get Access Token from cache.
762
+ try {
763
+ const account = this.msalInstance.getAccountByUsername(this.loginHint);
764
+ const scopesRequestForAcquireTokenSilent = {
765
+ scopes: scopesArray,
766
+ account: account !== null && account !== void 0 ? account : undefined,
767
+ redirectUri: `${domain}/blank-auth-end.html`,
768
+ };
769
+ tokenResponse = await this.msalInstance.acquireTokenSilent(scopesRequestForAcquireTokenSilent);
770
+ }
771
+ catch (error) {
772
+ const acquireTokenSilentFailedMessage = `Failed to call acquireTokenSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
773
+ internalLogger.verbose(acquireTokenSilentFailedMessage);
774
+ }
775
+ if (!tokenResponse) {
776
+ // If fail to get Access Token from cache, try to get Access token by silent login.
777
+ try {
778
+ const scopesRequestForSsoSilent = {
779
+ scopes: scopesArray,
780
+ loginHint: this.loginHint,
781
+ redirectUri: `${domain}/blank-auth-end.html`,
782
+ };
783
+ tokenResponse = await this.msalInstance.ssoSilent(scopesRequestForSsoSilent);
733
784
  }
734
- else {
735
- internalLogger.verbose("Cached access token is expired");
785
+ catch (error) {
786
+ const ssoSilentFailedMessage = `Failed to call ssoSilent. Reason: ${error === null || error === void 0 ? void 0 : error.message}. `;
787
+ internalLogger.verbose(ssoSilentFailedMessage);
736
788
  }
737
789
  }
738
- else {
739
- internalLogger.verbose("No cached access token");
790
+ if (!tokenResponse) {
791
+ const errorMsg = `Failed to get access token cache silently, please login first: you need login first before get access token.`;
792
+ internalLogger.error(errorMsg);
793
+ throw new ErrorWithCode(errorMsg, ErrorCode.UiRequiredError);
740
794
  }
741
- const accessToken = await this.getAndCacheAccessTokenFromSimpleAuthServer(scopeStr);
795
+ const accessToken = parseAccessTokenFromAuthCodeTokenResponse(tokenResponse);
742
796
  return accessToken;
743
797
  }
744
798
  }
@@ -763,65 +817,22 @@ class TeamsUserCredential {
763
817
  const ssoToken = await this.getSSOToken();
764
818
  return getUserInfoFromSsoToken(ssoToken.token);
765
819
  }
766
- async exchangeAccessTokenFromSimpleAuthServer(scopesStr, authCodeResult) {
767
- var _a, _b;
768
- const axiosInstance = await this.getAxiosInstance();
769
- let retryCount = 0;
770
- while (true) {
771
- try {
772
- const response = await axiosInstance.post("/auth/token", {
773
- scope: scopesStr,
774
- code: authCodeResult.code,
775
- code_verifier: authCodeResult.codeVerifier,
776
- redirect_uri: authCodeResult.redirectUri,
777
- grant_type: GrantType.authCode,
778
- });
779
- const tokenResult = response.data;
780
- const key = await this.getAccessTokenCacheKey(scopesStr);
781
- // Important: tokens are stored in sessionStorage, read more here: https://aka.ms/teamsfx-session-storage-notice
782
- this.setTokenCache(key, {
783
- token: tokenResult.access_token,
784
- expiresOnTimestamp: tokenResult.expires_on,
785
- });
786
- return;
787
- }
788
- catch (err) {
789
- if (((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.type) && err.response.data.type === "AadUiRequiredException") {
790
- internalLogger.warn("Exchange access token failed, retry...");
791
- if (retryCount < maxRetryCount) {
792
- await this.sleep(retryTimeSpanInMillisecond);
793
- retryCount++;
794
- continue;
795
- }
796
- }
797
- throw err;
798
- }
799
- }
800
- }
801
- /**
802
- * Get access token cache from authentication server
803
- * @returns Access token
804
- */
805
- async getAndCacheAccessTokenFromSimpleAuthServer(scopesStr) {
806
- try {
807
- internalLogger.verbose("Get access token from authentication server with scopes: " + scopesStr);
808
- const axiosInstance = await this.getAxiosInstance();
809
- const response = await axiosInstance.post("/auth/token", {
810
- scope: scopesStr,
811
- grant_type: GrantType.ssoToken,
812
- });
813
- const accessTokenResult = response.data;
814
- const accessToken = {
815
- token: accessTokenResult.access_token,
816
- expiresOnTimestamp: accessTokenResult.expires_on,
817
- };
818
- const cacheKey = await this.getAccessTokenCacheKey(scopesStr);
819
- this.setTokenCache(cacheKey, accessToken);
820
- return accessToken;
821
- }
822
- catch (err) {
823
- throw this.generateAuthServerError(err);
824
- }
820
+ async init() {
821
+ const ssoToken = await this.getSSOToken();
822
+ const info = getTenantIdAndLoginHintFromSsoToken(ssoToken.token);
823
+ this.loginHint = info.loginHint;
824
+ this.tid = info.tid;
825
+ const msalConfig = {
826
+ auth: {
827
+ clientId: this.config.clientId,
828
+ authority: `https://login.microsoftonline.com/${this.tid}`,
829
+ },
830
+ cache: {
831
+ cacheLocation: "sessionStorage",
832
+ },
833
+ };
834
+ this.msalInstance = new PublicClientApplication(msalConfig);
835
+ this.initialized = true;
825
836
  }
826
837
  /**
827
838
  * Get SSO token using teams SDK
@@ -891,16 +902,13 @@ class TeamsUserCredential {
891
902
  internalLogger.error(ErrorMessage.AuthenticationConfigurationNotExists);
892
903
  throw new ErrorWithCode(ErrorMessage.AuthenticationConfigurationNotExists, ErrorCode.InvalidConfiguration);
893
904
  }
894
- if (config.initiateLoginEndpoint && config.simpleAuthEndpoint && config.clientId) {
905
+ if (config.initiateLoginEndpoint && config.clientId) {
895
906
  return config;
896
907
  }
897
908
  const missingValues = [];
898
909
  if (!config.initiateLoginEndpoint) {
899
910
  missingValues.push("initiateLoginEndpoint");
900
911
  }
901
- if (!config.simpleAuthEndpoint) {
902
- missingValues.push("simpleAuthEndpoint");
903
- }
904
912
  if (!config.clientId) {
905
913
  missingValues.push("clientId");
906
914
  }
@@ -908,111 +916,20 @@ class TeamsUserCredential {
908
916
  internalLogger.error(errorMsg);
909
917
  throw new ErrorWithCode(errorMsg, ErrorCode.InvalidConfiguration);
910
918
  }
911
- /**
912
- * Get axios instance with sso token bearer header
913
- * @returns AxiosInstance
914
- */
915
- async getAxiosInstance() {
916
- const ssoToken = await this.getSSOToken();
917
- const axiosInstance = axios.create({
918
- baseURL: this.config.simpleAuthEndpoint,
919
- });
920
- axiosInstance.interceptors.request.use((config) => {
921
- config.headers.Authorization = "Bearer " + ssoToken.token;
922
- return config;
923
- });
924
- return axiosInstance;
925
- }
926
- /**
927
- * Set access token to cache
928
- * @param key
929
- * @param token
930
- */
931
- setTokenCache(key, token) {
932
- Cache.set(key, JSON.stringify(token));
933
- }
934
- /**
935
- * Get access token from cache.
936
- * If there is no cache or cannot be parsed, then it will return null
937
- * @param key
938
- * @returns Access token or null
939
- */
940
- getTokenCache(key) {
941
- const value = Cache.get(key);
942
- if (value === null) {
943
- return null;
944
- }
945
- const accessToken = this.validateAndParseJson(value);
946
- return accessToken;
947
- }
948
- /**
949
- * Parses passed value as JSON access token, if value is not a valid json string JSON.parse() will throw an error.
950
- * @param jsonValue
951
- */
952
- validateAndParseJson(jsonValue) {
919
+ setSessionStorage(sessonStorageValues) {
953
920
  try {
954
- const parsedJson = JSON.parse(jsonValue);
955
- /**
956
- * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
957
- * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
958
- * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
959
- *
960
- */
961
- return parsedJson && typeof parsedJson === "object" ? parsedJson : null;
921
+ const sessionStorageKeys = Object.keys(sessonStorageValues);
922
+ sessionStorageKeys.forEach((key) => {
923
+ sessionStorage.setItem(key, sessonStorageValues[key]);
924
+ });
962
925
  }
963
926
  catch (error) {
964
- return null;
965
- }
966
- }
967
- /**
968
- * Generate cache key
969
- * @param scopesStr
970
- * @returns Access token cache key, a key example: accessToken-userId-clientId-tenantId-scopes
971
- */
972
- async getAccessTokenCacheKey(scopesStr) {
973
- const ssoToken = await this.getSSOToken();
974
- const ssoTokenObj = parseJwt(ssoToken.token);
975
- const clientId = this.config.clientId;
976
- const userObjectId = ssoTokenObj.oid;
977
- const tenantId = ssoTokenObj.tid;
978
- const key = [accessTokenCacheKeyPrefix, userObjectId, clientId, tenantId, scopesStr]
979
- .join(separator)
980
- .replace(/" "/g, "_");
981
- return key;
982
- }
983
- /**
984
- * Check whether the token is about to expire (within 5 minutes)
985
- * @returns Boolean value indicate whether the token is about to expire
986
- */
987
- isAccessTokenNearExpired(token) {
988
- const expireDate = new Date(token.expiresOnTimestamp);
989
- if (expireDate.getTime() - Date.now() > tokenRefreshTimeSpanInMillisecond) {
990
- return false;
927
+ // Values in result.sessionStorage can not be set into session storage.
928
+ // Throw error since this may block user.
929
+ const errorMessage = `Failed to set values in session storage. Error: ${error.message}`;
930
+ internalLogger.error(errorMessage);
931
+ throw new ErrorWithCode(errorMessage, ErrorCode.InternalError);
991
932
  }
992
- return true;
993
- }
994
- generateAuthServerError(err) {
995
- var _a, _b;
996
- let errorMessage = err.message;
997
- if ((_b = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.type) {
998
- errorMessage = err.response.data.detail;
999
- if (err.response.data.type === "AadUiRequiredException") {
1000
- const fullErrorMsg = "Failed to get access token from authentication server, please login first: " +
1001
- errorMessage;
1002
- internalLogger.warn(fullErrorMsg);
1003
- return new ErrorWithCode(fullErrorMsg, ErrorCode.UiRequiredError);
1004
- }
1005
- else {
1006
- const fullErrorMsg = "Failed to get access token from authentication server: " + errorMessage;
1007
- internalLogger.error(fullErrorMsg);
1008
- return new ErrorWithCode(fullErrorMsg, ErrorCode.ServiceError);
1009
- }
1010
- }
1011
- const fullErrorMsg = "Failed to get access token with error: " + errorMessage;
1012
- return new ErrorWithCode(fullErrorMsg, ErrorCode.InternalError);
1013
- }
1014
- sleep(ms) {
1015
- return new Promise((resolve) => setTimeout(resolve, ms));
1016
933
  }
1017
934
  }
1018
935