@aws-amplify/auth
Version:
Auth category of aws-amplify
1 lines • 13.4 kB
Source Map (JSON)
{"version":3,"file":"credentialsProvider.mjs","sources":["../../../../../src/providers/cognito/credentialsProvider/credentialsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger, getCredentialsForIdentity, } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { getRegionFromIdentityPoolId } from '../utils/clients/CognitoIdentityProvider/utils';\nimport { assertIdTokenInAuthTokens } from '../utils/types';\nimport { cognitoIdentityIdProvider } from './IdentityIdProvider';\nimport { formLoginsMap } from './utils';\nconst logger = new ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nexport class CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n assertIdentityPoolIdConfig(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await cognitoIdentityIdProvider({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n assertIdTokenInAuthTokens(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? formLoginsMap(authTokens.idToken.toString())\n : {};\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'primary',\n });\n }\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAQA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,4BAA4B,CAAC,CAAC;AAC/D,MAAM,eAAe,GAAG,EAAE,GAAG,E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