Amplify-cli: Use existing Cognito User pool with amplify auth

Created on 28 Jan 2019  Â·  70Comments  Â·  Source: aws-amplify/amplify-cli

Hi,
I'm working on an android project with amplify. I find it very powerful but it also hides lot of complexity. So...

Is it possible to use amplify with an existing Cognito User pool I already configured.

amplify add auth (I would like to specify my own user pool and not create a new one)

This is already possible for appsync
amplify add codegen --apiId XXXXXXXXXXXXXXXXXXXXXXXX

More generally I would like to swith my configuration from dev to prod env

Thanks,

auth feature-request

Most helpful comment

in my use case, we're tying do modularize the project so that any new amplify projects could use the same Cognito pool that's already setup. example, we have 2 API endpoints (userdata and payment), we'd like development of those APIs to be independent (separate teams, separate repository), but have them still share the same Cognito to allow all the @auth transform directives to work in the GQL schema with this existing AUTH endepoint

ideally we'd be able to do

amplify add auth --poolARN arn:aws:cognito-idp:eu-west-1:500880489372:userpool/eu-west-1_4DFTecsHs

the current amplify project does not need to load all the configuration and redeploy the AUTH component, but can still use this configuration to automatically set the Amplify API with relevant information.

All 70 comments

More generally I would like to swith my configuration from dev to prod env

Do you use multienv? If yes, you may find what you are looking for in the docs:
https://aws-amplify.github.io/docs/cli/multienv?sdk=js
There are a couple of examples on how to switch environments.

Regarding the existing User Pool, I don't think there is an existing solution for that. I think you can either transfer all accounts from one user pool to another (and have them change their pw) or edit the reference in the cloudformation file by hand. Though I would not recommend that second "solution" since it is prone to errors.

BR

Thanks
I'm currently exploring multienv but it's in beta... Even with this you cannot provide your own Cognito User Pool. This is annoying since some properties of the User pool cannot be updated after the creation

The Properties of the user pool can be configured upon the creation, even with amplify.

I was asking for the multienv because of your other question regarding switching between prod and dev. This has nothing to do with the user pool afaik.

Edit: yeah it kind of sucks that you cannot add an existing User Pool since this already worked with mobile hub

You don't need to edit cloudformation templates in order to add a customer user pool. Most of the backend resources you create with Amplify have a parameters.json file associated with them. The values in this file are passed as parameters to the associated cloudformation template. For example, for a GraphQL API, you can replace the value under the key AuthCognitoUserPoolId in parameters.json.

You'll also want to overwrite some values in the frontend - for example, in a ReactJS project, you'll want to add aws_cognito_identity_pool_id, aws_cognito_region, aws_user_pools_id, and aws_user_pools_web_client_id to the awsMobile object that you pass in to Amplify.configure().

Note that this method requires you to manually edit parameters.json for each backend resource you want to hook into your custom cognito pool. I also don't know if performing an amplify edit on any of these resources will blow away your changes.

Hi zjullion so updating the parameters.json seems to be a good idea

I was thinking about something like the following

amplify auth add

Then edit amplify/backend/auth/cognitoxxx/parameters.json and update the userPoolName

    "identityPoolName": "cognitoxxxxx_identitypool_xxxxx",
    "allowUnauthenticatedIdentities": false,
    "thirdPartyAuth": false,
    "lambdaLogPolicy": "cognitofxxxxx_lambda_log_policy",
    "openIdLambdaRoleName": "cognitoxxxxx_openid_lambda_role",
    "openIdRolePolicy": "cognitofcxxxxx_openid_pass_role_policy",
    "openIdLambdaIAMPolicy": "cognitofxxxxx_openid_lambda_iam_policy",
    "openIdLogPolicy": "cognitofcxxxxx_openid_lambda_log_policy",
    "userPoolName": "__%MY_CUSTOM_USER_POOL_NAME%__",

then amplify push

I can then even write a custom script with appropriate placeholders to switch from 1 env to another.
I will also have to update the profile in ./config/aws-info.json

What do you think about that ?
I Will try

Thanks

slaat, I you create a User Pool with some required attributes you cannot change these requirements after the user pool is created following Cognito User pools doc (Search for "To edit standard attributes")

If you're using an existing user pool, don't do amplify auth add at all - just update the parameters.json for the other backend resources to point to your custom user pool.

But amplify auth is not only about UserPoolName. I need to set the other parameters listed above. Right?

Also when you say updating parameters.json for other backend resources, is adding "userPoolName": "__%MY_CUSTOM_USER_POOL_NAME%__", in the files enough ?

Actually If amplify auth works I prefer to use it. I will then remove all the duplicated settings from parameters.json and keep all the config on my custom UserPool.

Also when you say updating parameters.json for other backend resources, is adding "userPoolName": "__%MY_CUSTOM_USER_POOL_NAME%__", in the files enough ?

This doesn't seem to work. It will create a new User Pool with that name and generally the default settings. I want to be able to create a User Pool to use in my app that uses a different set of attributes (since they can't be changed later) but even if I change values in the parameters.json, it creates a new pool with default values.

Hey guys, if you want to use an already configured user pool, you can manually add it to your client-side code. For more details, look at - https://aws-amplify.github.io/docs/js/authentication#manual-setup

Amplify CLI uses Cloudformation to deploy and manage resources and unfortunately, Cloudformation doesn't allow you to manage existing resources, so you won't be able to manage an already existing resource using the Amplify CLI for now.

although manually configuring gets it to work, this does not allow user files with the amplify add storage - it notifies that
You need to add auth (Amazon Cognito) to your project in order to add storage for user files. Do you want to add auth now?

it appears that with the manual config amplify does not see a valid Auth available..?

My app uses Lambda Function, APIGW and GraphQL Api. I did not execute amplify add auth but I see Auth resource cognitoab3b5d1a getting created. I tried to modify amplify/backend/auth/cognitoab3b5d1a/parameters.json in identityPoolName field with the value generated in the previous project (beta_user_pool-beta) I executed amplify add auth but when I try pushing it I get:

CREATE_FAILED      IdentityPool                                            AWS::Cognito::IdentityPool   Wed Feb 27 2019 10:18:10 GMT-0800 (Pacific Standard Time) 1 validation error detected: Value 'beta_user_pool-beta__alpha' at 'identityPoolName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w ]+ (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: ValidationException; Request ID: 09c35705-3abc-11e9-880b-075cf15fcc0b)
CREATE_FAILED      pallet-20190227092009-authcognitoab3b5d1a-1EARGAMZ2F6ZY AWS::CloudFormation::Stack   Wed Feb 27 2019 10:18:11 GMT-0800 (Pacific Standard Time) The following resource(s) failed to create: [IdentityPool].

When I remove the default auth amplify remove auth cognitoab3b5d1a and try to push it I get

✖ An error occurred when pushing the resources to the cloud

Template error: instance of Fn::GetAtt references undefined resource authcognitoab3b5d1a

What am I doing wrong?

UPDATE: even I add the default auth that I removed above I still get an error about missing auth:

â § Updating resources in the cloud. This may take a few minutes...Error updating cloudformation stack
✖ An error occurred when pushing the resources to the cloud

Template error: instance of Fn::GetAtt references undefined resource authcognitoab3b5d1a

To be clear about the scenario we want to enable. We want to enable A/B testing where we have users from the same pool using the app with different UX. We also have single S3 bucket an Aurora DB that centralize the content.

I stumbled across this, too. In my case, I want to:

  • let the user sign in with email (instead of username, which is the default)

I cannot set this if using amplify add auth, so I'm forced to create a user pool via the AWS web interface. But then I cannot easily associate this user pool with my client app. If I try to follow the manual setup (i.e. using the provided userpool id and client id), I always get an error:

Unable to verify secret hash for client ####

It would be awesome, if amplify add auth could allow to set the "sign in with email" option and if manual setup would work without errors.

@morgler for that you need to make sure your client doesn't have a client secret. Another hidden gem in AWS configuration black hole.

Screen Shot 2019-05-14 at 13 34 01

You don't need to edit cloudformation templates in order to add a customer user pool. Most of the backend resources you create with Amplify have a parameters.json file associated with them. The values in this file are passed as parameters to the associated cloudformation template. For example, for a GraphQL API, you can replace the value under the key AuthCognitoUserPoolId in parameters.json.

You'll also want to overwrite some values in the frontend - for example, in a ReactJS project, you'll want to add aws_cognito_identity_pool_id, aws_cognito_region, aws_user_pools_id, and aws_user_pools_web_client_id to the awsMobile object that you pass in to Amplify.configure().

Note that this method requires you to manually edit parameters.json for each backend resource you want to hook into your custom cognito pool. I also don't know if performing an amplify edit on any of these resources will blow away your changes.

*Hey @zjullion where do i find parameters.json on my file tree? Please advise. also i was advised to use this method (https://github.com/aws-amplify/aws-sdk-android/issues/578)... which one would be better, also i need to add 2 cognito userpools am i able to do both userpools in ... either parameters.json, or "awsconfiguration.json" at the same time?

THank you *

@ravnarayan, I wrote a bit of a scrambled Medium post on this exact problem. I had to get into the amplify/backend/auth/auth/auth-cloudformation-template.yml file and edit it as well to get a custom Cognito pool spun up for my app. I hope this helps; let me know if you need more explanation after reading through it.

Hey @DanielCender

Thank you very much for helping m out... I tried following your instructions but on my Amplify File tree auth-cloudformation-template.yml does not exist. I have created the full stack but have error issues completing it as well... do you think it will show once push is completed?

Rav,

Hey @DanielCender

actually i do see it, mine is /amplify/backend/auth/cognito/cognito-cloudformation-template.yml... sorry about the last message... my schema is on line 176... Also, I'm not very good at this... what would i put here?

thank you,

I have red above discussion and from my POV it looks like it is not clear how to connect Amplify to existing user pool. Is it not possible to just modify aws-exports.ts and get it done? Why Amplify forces to create AWS settings from the console while it is not the most popular use case scenario?

It worked for me. Had two apps (App A and App B) which I wanted to work off of the same userpool. Since the aws-exports.js file is autogenerated for App B, my webpack build creates a copy of the file and modifies the aws_cognito_identity_pool_id, aws_cognito_region, aws_user_pools_id and aws_user_pools_web_client_id to point to the attribute values of App A, whose user pool I wanted to use. I then updated the input to AWS.configure to point to the edited file.

I did modify some of the IAM policies for App A so that the the IAM credentials obtained by App B via the identity pool of App A, provided access to the resources created by the App B.

@bindhyeswari I was not able to find any aws_cognito_identity_pool_id or other pools id under any of the parameters.json files I have.

find ./ -name "parameters.json"| xargs grep aws_user_pools_web_client_id

I assume the change is required under AppSync and API GW backend but I can't find what and where.

I tried this as well and realized that this violates the philosophy of Amplify. At least against the present version.
The idea behind Amplify is that a completely independent application is defined here. This also includes a DB with an API, authentication, etc. Since the application has certain expectations of the services, they can or should be defined in the project. This is done by AWS Cloudformation.
For this reason, the CLI works well only if it has the AWS Cloudformation configurations created with the amplify add <service>.
So if we have a user pool, we are forced to export the users from it and import them into the by the application defined user pool.

In our case we had an existing user pool that was a dependancy of multiple platforms, so it would not work via the Amplify CLI to integrate that existing user pool and have it be part of our Cloudformation templates for the web platform (the templates for that user pool already existing elsewhere). It was a non issue though, we did the manual setup and injected the Cognito configs via Environment Variables and it worked like a charm. For applications that are part of a larger system I think this is totally okay.

Part of the original issue was that there are a lot of configuration options on user pools that were not configurable in amplify and we not changeable once the user pool is created. So in addition to the case that @jhoffmcd mentions (existing user pool from another project), I wanted a way of configuring all of the settings that we can get in a user pool within amplify. I think it is better than it was back in January, I haven't tried lately to see where the differences still are.

@poppybank I am not particularly experienced with AWS Cloudformation, but should not it be possible to change this to the Cloudformation configuration file after defining Auth and before the push? And should not it be possible to change it there afterwards? Of course this means it create a new cognito service.

I think specifying that you want to use am existing pool would be a nice CLI option, however I don't think there would be any point in templatizing that in CloudFormation since that resource is already created (and maybe already has a template somewhere else?). Really, all the app really needs to do auth is all available in the Auth class import.

@alexanderVu be aware that some changes you make to Cloudformation templates completely replace the resource, so if you have users in your user pool and you push the changes it won't migrate those users for you, you will have to take care of that.

in my use case, we're tying do modularize the project so that any new amplify projects could use the same Cognito pool that's already setup. example, we have 2 API endpoints (userdata and payment), we'd like development of those APIs to be independent (separate teams, separate repository), but have them still share the same Cognito to allow all the @auth transform directives to work in the GQL schema with this existing AUTH endepoint

ideally we'd be able to do

amplify add auth --poolARN arn:aws:cognito-idp:eu-west-1:500880489372:userpool/eu-west-1_4DFTecsHs

the current amplify project does not need to load all the configuration and redeploy the AUTH component, but can still use this configuration to automatically set the Amplify API with relevant information.

Maybe this is not directly related to this topic but wanted to see if anyone has the same issue that I'm having. We know that we can't change the Cognito setting once created but Amplify CLI does not seem to offer to check Also allow sign in with verified email address with username sign-in during the set up process of amplify auth add.

image

I really feel like there's another following question after selecting username as a sign up method that asking if I want to allow verified email or phone numbers sign-in.

Does anyone know the way to get around this? So I can have a user sign-in with username or email address?

I'm also seeing an error when using an external uesrpool that seems related to https://github.com/aws-amplify/amplify-js/issues/3405 . The documentation for manual setup (https://aws-amplify.github.io/docs/js/authentication#manual-setup) seems to be missing an oauth field, too.

Our plan was to use Amplify to generate several independent applications, but use a single Cognito User Pool, with a single User dynamoDb table, serving as SSO for all of them.

Understood that on the front-end side I can switch credentials in aws-exports.js, and refer to SSO Cognito User Pool, but how would I go about integrating the rest of the backend components per each application? Should I create a new Auth for each application, and how do I connect it to SSO?

Is this achievable, and what would be the best approach to handle it? Thanks!

I have a similar use case to @asmajlovicmars. I'd like to provision my backend resources using terraform, to integrate with my existing infrastructure (which is also provisioned via terraform).

I need cognito and my app sync API to integrate as well.

I also plan to have multiple amplify projects integrate with the same user pool.

Is there an RFC for this? This should be prioritized.

So if you are using a centralized user pool for multiple apps, I think you will want to manually set up your Cognito integration and just use a manual configuration as noted here: https://aws-amplify.github.io/docs/js/authentication#manual-setup

We have several clients (web, ios, android) using a centralized backend which includes a shared user pool. In this scenario, we don't use authentication as set up by the Amplify CLI, because that would set up a CloudFormation template that would provision new resources for each client application.

Perhaps the feature request here is that the CLI tool allows you to configure a new project with Auth where you can specify an external existing Cognito service, rather than having Amplify provision one for you?

For now, I'll try creating a backend repository containing the user pool as detailed here: https://aws-amplify.github.io/docs/cli-toolchain/quickstart#multiple-frontends

Edit: with a terraform module to output the user pool and other things.

Maybe this is not directly related to this topic but wanted to see if anyone has the same issue that I'm having. We know that we can't change the Cognito setting once created but Amplify CLI does not seem to offer to check Also allow sign in with verified email address with username sign-in during the set up process of amplify auth add.

image

I really feel like there's another following question after selecting username as a sign up method that asking if I want to allow verified email or phone numbers sign-in.

Does anyone know the way to get around this? So I can have a user sign-in with username or email address?

No need of any other configs, but you can definitely add this config to the current amplify tool. Most apps need this badly

Sad to see this isn't addressed. I finally moved away from Amplify, because without such a basic feature it is unusable for production. I like the intention of Amplify and I'm willing to go through some pain with new libraries. But not much has changed over the past 7 months on several core issues and so I must assume Amplify has no active support anymore.

To everybody with similar Amplify issues: I moved to serverless.com, which – despite being more complicated than Amplify – seems much more mature and flexible. I still use Amplify for Cognito auth, since it seems Cognito client libs are only available within Amplify. This is however just a crippled Amplify without using the CLI.

I'd be happy to try Amplify a third time in another 7 months, but until then I have production code to write. I wish you guys all the best and hope you can get support for actively maintaining and improving Amplify!

Sad to see this isn't addressed. I finally moved away from Amplify, because without such a basic feature it is unusable for production. I like the intention of Amplify and I'm willing to go through some pain with new libraries. But not much has changed over the past 7 months on several core issues and so I must assume Amplify has no active support anymore.

To everybody with similar Amplify issues: I moved to serverless.com, which – despite being more complicated than Amplify – seems much more mature and flexible. I still use Amplify for Cognito auth, since it seems Cognito client libs are only available within Amplify. This is however just a crippled Amplify without using the CLI.

I'd be happy to try Amplify a third time in another 7 months, but until then I have production code to write. I wish you guys all the best and hope you can get support for actively maintaining and improving Amplify!

@morgler apologies that this specific issue hasn't been clarified even though we did tag it as a feature request. Amplify is very much actively supported with multiple teams across the libraries, CLI, and UI components. There is still only so much that we can accomplish though when weighing customer requests and technical challenges.

As others have noted in this thread Amplify does support deploying new resources however importing and managing existing resources into Amplify projects isn't supported today. You can manually update your configuration files but if you wanted to take an existing User Pool, AppSync API, S3 bucket, etc. and have Amplify manage that resource we don't support it currently.

However we are looking to support this in the future and have it as an item we're currently investigating this year. The technical challenge is that Amplify uses CloudFormation under the covers which up until late last year it didn't have this capability. Now that it has been released we are working with Cognito and other teams to have them onboard this functionality and achieve coverage under the Resource Import service list. This will take some time (I have no timelines) however it is very much on our radar.

@undefobj ok, if this is still not supported, can you please suggest a workaround for production environment. Let me describe the issue:

  1. you create production evn
  2. you do new features, add resources, lambdas, etc.
  3. update fails and it rolls back (manual delete of nested stack I believe will break your amplify deploy cause it is no longer in sync, don't see any other option here, unless you can share some)
  4. the only choice is to remove the env and re-create it - and the deploy will pass successfully in this case.
  5. when doing so we loose production cognito + dynamoDB, and we don't want that we need to keep them cause this is production!
  6. Let's assume we add deletion policy to Retain for both resources, this gives us nothing cause you can't reuse them. Creating a custom transformer would let's say solve the usage of existing DynamoDB resource, but for cognito I see no workaround at all ...

So the problem is not necessarily that we can't use existing resources, cause we can init only once and then just reuse same resources, but the fact that on a failure there is nothing to do to keep current deployment + new features added. I hope it makes sense. If there would be a possibility to do continuous delivery of features to a project using existing environment all the time this issues wouldn't be open.

@undefobj ok, if this is still not supported, can you please suggest a workaround for production environment. Let me describe the issue:

  1. you create production evn
  2. you do new features, add resources, lambdas, etc.
  3. update fails and it rolls back (manual delete of nested stack I believe will break your amplify deploy cause it is no longer in sync, don't see any other option here, unless you can share some)
  4. the only choice is to remove the env and re-create it - and the deploy will pass successfully in this case.
  5. when doing so we loose production cognito + dynamoDB, and we don't want that we need to keep them cause this is production!
  6. Let's assume we add deletion policy to Retain for both resources, this gives us nothing cause you can't reuse them. Creating a custom transformer would let's say solve the usage of existing DynamoDB resource, but for cognito I see no workaround at all ...

So the problem is not necessarily that we can't use existing resources, cause we can init only once and then just reuse same resources, but the fact that on a failure there is nothing to do to keep current deployment + new features added. I hope it makes sense. If there would be a possibility to do continuous delivery of features to a project using existing environment all the time this issues wouldn't be open.

@xoadrian This issue is related to adding existing resources and your ask seems to be related to recovering a stack after failed push. You would do this with amplify env pull --restore. I would ask though if you need assistance with this you open up a new issue as it's unrelated to this thread.

Do I understand correctly that you cannot use the @auth directive without using amplify add auth? I've been using the linked Manual Setup on the client side, but without Amplify + CloudFront explicitly managing the user pool, I won't be able to use the @auth directive in my schema?

This would be very unfortunate. The two main reasons that we cannot currently allow Amplify to provision the auth are:

  1. Not enough configuration options for login method (only email and password)
  2. Lack of support for multi auth. We need to have two different user pools.

Given these things, we are maintaining those user pools outside of Amplify. But if we cannot use Amplify with existing pools, it makes Amplify unusable for us.

Hey @isaiahtaylor, sorry but that’s incorrect, just use amplify... and don’t use addauth once your application on amplify is complied add an external auth provider... this will require manual code from your and your frontend team.. now there is not much support on adding post Cognito auth, but when your setting up amplify you can’t edit a exports.js file.. you would just add auth on app.js and your auth is good to go...

Hopefully this helps, thank you

Hello all, I've carved out a workaround for this.

  1. amplify add auth and name it something like "thisisfake" to tell yourself you won't be using it. Go through all the needed steps. This will create an auth directory under amplify/backend.
  2. amplify update api this will modify your api to include authorization. It will also set up your CloudFormation stacks to reference the Cognito pool that will be provisioned in amplify/backend/auth. Everything so far is happy path and non-hacky.
  3. Ok here's the magic. Running amplify update api will add a property to amplify/backend/api/frontendapi/parameters.json called AuthCognitoUserPoolId. It will be a function block that CloudFormation will fill in once it provisions the Cognito pool. Simply replace this { ... function block... } with your existing pool ID. It should look like:
{
  "other stuff": "etc",
  "AuthCognitoUserPoolId": "XXX"
}
  1. amplify push
  2. Check this change into source control. amplify/backend/api/frontendapi/parameters.json is already a tracked file. You will not need to modify this again, unless you change your auth setup and that parameters.json gets overridden. If that's the case, just pop your ID in there again.

A caveat: You will have a Cognito pool called "thisisfake" sitting in AWS Cognito. But it will be empty. You can go to AppSync and verify that your app is in fact pointing at the ID you specified.

I'm able to use @auth in my schema.graphql perfectly fine!

If you're using an existing user pool, don't do amplify auth add at all - just update the parameters.json for the other backend resources to point to your custom user pool.

@zjullion correct me if I am wrong, but that solution does not allow the use of the amplify @auth directives. It will fail, telling you that it can't create auth logic in your resolvers because no auth has been configured for it. My solution allows for using @auth.

Hi @isaiahtaylor, I should expand, as my initial comment wasn't fully correct, and I shouldn't have just replied with it without investigating more:

You don't need to run amplify add auth, as amplify will create auth as part of amplify add api (if you don't have auth already) - however, you can remove all of the auth resources (and subsequently not deploy them to the cloud) if you're referencing an existing user pool:

  1. Delete backend/auth and everything under it
  2. Modify parameters.json as you've described above
  3. Modify backend-config.json to remove the top-level auth section, and update your api's authConfig as follows (remove the reference to the auth pool):
"authConfig": {
  "additionalAuthenticationProviders": [],
  "defaultAuthentication": {
    "authenticationType": "AMAZON_COGNITO_USER_POOLS"
  }
}
  1. Run amplify env checkout <environment> -> you need to do this or amplify won't pick up your changes

Viola! You can add @auth directives in your schema.graphql and everything will work as expected.

@zjullion thanks! I'll try that out, it would be nice to not have a floating pool in AWS.

@zjullion, @isaiahtaylor thanks for your contributions - worked for me!

@zjullion @isaiahtaylor Would one of you guys mind pasting a full example of the the json around the parameters.json and backend-config.json? Just the stuff around the added api that will use the existing user pool as the authorizer. I tried doing what I think the above steps meant and I am getting this error when I push:

Parameters: [AuthCognitoUserPoolId] do not exist in the template

I deleted the backend/auth and I see after rechecking out the env that is no longer in the status as expected. I dropped the authConfig bit into the api's object in backend-config.json:

"Temp": {
   "service": "API Gateway",
   "providerPlugin": "awscloudformation",
   "dependsOn": [
        {
           "category": "function",
           "resourceName": "SomeFunction",
            "attributes": [
                 "Name",
                 "Arn"
             ]
         }
      ],
    "authConfig": {
    "additionalAuthenticationProviders": [],
    "defaultAuthentication": {
        "authenticationType": "AMAZON_COGNITO_USER_POOLS"
     }
  }
}

in backend/api/Temp/parameters.json

{
    "authRoleName": {
        "Ref": "AuthRoleName"
    },
    "unauthRoleName": {
        "Ref": "UnauthRoleName"
    },
   "AuthCognitoUserPoolId": "MY-ID-HERE"   // I assume this is not correct?
}

Thank you!

@smakinson My JSON looks the same as yours, but I have two thoughts:

  1. My api is an AppSync, not API Gateway. I've never deploying an API Gateway with amplify-cli, so I'm not sure if it respects / uses the same arguments in parameters.json.
  2. Did you run amplify env checkout <environment> after making your changes?

@zjullion Thanks for the response. Do you know if the format for the json files is documented anywhere? I did recheck out the environment after, I noticed the Auth category stayed in the status until after I ran that command.

Sorry @smakinson, I don't think it is.

Hi,
I already have a web application built in Vue.js using the AWS Cognito user pool with email and password authentication. Now I am developing mobile interface of the same web application using expo-web (React Native) and want to use the existing cognito user pool.

I tried to use by adding aws-amplify and configuring the user pool id, region and webclient id but it does not give me the access token and does not return any response or error.

Am I missing something here? Do I need to execute amplify init even if I already have the user pool details?

Please suggest.
Thanks!!

https://docs.amplify.aws/lib/auth/start/q/platform/js#re-use-existing-authentication-resource

This issue is about having support for existing authentication resources in the CLI not the JS library.

@zjullion @isaiahtaylor also worked for me to link AppSync to an existing Cognito instance, thanks. Hopefully soon we can do this via the CLI.

Hi,

How you configure this with amplify iOS library? The documentation only shows how to do that with js. Using existing api's or auth is not documented for iOS library.

Hello all, I've carved out a workaround for this.

  1. amplify add auth and name it something like "thisisfake" to tell yourself you won't be using it. Go through all the needed steps. This will create an auth directory under amplify/backend.
  2. amplify update api this will modify your api to include authorization. It will also set up your CloudFormation stacks to reference the Cognito pool that will be provisioned in amplify/backend/auth. Everything so far is happy path and non-hacky.
  3. Ok here's the magic. Running amplify update api will add a property to amplify/backend/api/frontendapi/parameters.json called AuthCognitoUserPoolId. It will be a function block that CloudFormation will fill in once it provisions the Cognito pool. Simply replace this { ... function block... } with your existing pool ID. It should look like:
{
  "other stuff": "etc",
  "AuthCognitoUserPoolId": "XXX"
}
  1. amplify push
  2. Check this change into source control. amplify/backend/api/frontendapi/parameters.json is already a tracked file. You will not need to modify this again, unless you change your auth setup and that parameters.json gets overridden. If that's the case, just pop your ID in there again.

A caveat: You will have a Cognito pool called "thisisfake" sitting in AWS Cognito. But it will be empty. You can go to AppSync and verify that your app is in fact pointing at the ID you specified.

I'm able to use @auth in my schema.graphql perfectly fine!

Does anyone have a workaround that can be used with multiple environments/cognito pools? Assuming there is a prod and dev environment, both would be hardcoded to the same pool with this strategy.

@seanvm my team has a number of 'pre-deploy' node scripts that we run to update values in cloudformation templates / config files before deploying our amplify-cli app. Basically, you can have multiple environments / cognito pools, but you need to write custom scripts to do that.

@seanvm my team has a number of 'pre-deploy' node scripts that we run to update values in cloudformation templates / config files before deploying our amplify-cli app. Basically, you can have multiple environments / cognito pools, but you need to write custom scripts to do that.

Any chance you could give a sample of how to do this? I would like to set up a similar set up running multiple environments as well. I've tried your solution above involving deleting the bakend auth folder from your local machine, but this led to my analytics features not working. I then tried the other workaround and it did work, although now I have an extra userpool sitting in the cloud that isn't being used. I was able to delete it on the cognito pools page and the analytics tracking still works. I think it has to do with the fact that in this solution, the CLI still thinks there is a backend resource for auth and recognizes it, whereas with your solution, once you do the env checkout the CLI seems to recognize that you have no auth. Since the analytics module depends on auth I would guess it doesn't try to send events if there appears to be no auth.

I've tried your solution above involving deleting the bakend auth folder from your local machine, but this led to my analytics features not working.

PinPoint analytics works via IAM, not Cognito, and so I suspect there's something missing / strange going on with auth not present. We have a custom cloudformation template to get PinPoint working without the auth resource.

@seanvm my team has a number of 'pre-deploy' node scripts that we run to update values in cloudformation templates / config files before deploying our amplify-cli app. Basically, you can have multiple environments / cognito pools, but you need to write custom scripts to do that.

Any chance you could give a sample of how to do this?

Under api/myapiname, you'll have a parameters.json file. The key you want to overwrite is AuthCongitoUserPoolId. Basically, we just have a node script that, based on the amplify environment you have checked out, modifies the value here to point to the correct cognito pool.

hi folks - we are actively looking into this issue now as part of a broader "import feature". More to follow here: #3977

I've tried your solution above involving deleting the bakend auth folder from your local machine, but this led to my analytics features not working.

PinPoint analytics works via IAM, not Cognito, and so I suspect there's something missing / strange going on with auth not present. We have a custom cloudformation template to get PinPoint working without the auth resource.

@seanvm my team has a number of 'pre-deploy' node scripts that we run to update values in cloudformation templates / config files before deploying our amplify-cli app. Basically, you can have multiple environments / cognito pools, but you need to write custom scripts to do that.

Any chance you could give a sample of how to do this?

Under api/myapiname, you'll have a parameters.json file. The key you want to overwrite is AuthCongitoUserPoolId. Basically, we just have a node script that, based on the amplify environment you have checked out, modifies the value here to point to the correct cognito pool.

I am trying to do a similar thing with cloudformation, did you have to go through any additional steps other than simply creating the dashboard and then adding the id and region to Amplify.configure? I attached a policy to the unauth/auth roles to access the cloudformation created pinpoint, but it's giving unhandled promise rejections when I try to run and record events.

Hi @isaiahtaylor, I should expand, as my initial comment wasn't fully correct, and I shouldn't have just replied with it without investigating more:

You don't need to run amplify add auth, as amplify will create auth as part of amplify add api (if you don't have auth already) - however, you can remove all of the auth resources (and subsequently not deploy them to the cloud) if you're referencing an existing user pool:

1. Delete `backend/auth` and everything under it

2. Modify `parameters.json` as you've described above

3. Modify `backend-config.json` to remove the top-level `auth` section, and update your `api`'s `authConfig` as follows (remove the reference to the auth pool):
"authConfig": {
  "additionalAuthenticationProviders": [],
  "defaultAuthentication": {
    "authenticationType": "AMAZON_COGNITO_USER_POOLS"
  }
}
1. Run `amplify env checkout <environment>` -> you need to do this or amplify won't pick up your changes

Viola! You can add @auth directives in your schema.graphql and everything will work as expected.

In my case, I had to go to my AWS Appsync Console for the generated Api, and in the "Settings" tab update my "Default authorization mode" settings, to manually select the user pool I wanted to use for authentication. Make sure to click "Save" as well after any changes.

@zjullion Thanks for the response. Do you know if the format for the json files is documented anywhere?

Here Here if this is what u asked for.

Hi, i am facing issue in android to use existing user pool. to use existing pool i am changing pool id , AppClientId, AppClientSecret in amplifyconfiguration.json. In this process sign up operation is working correctly but i am getting error for Sign in.

Error is like....
AWS Sign In issue - Failed to federate tokens during sign-in java.lang.RuntimeException: Error in federating the token
Invalid identity pool configuration. Check assigned IAM roles for this pool. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidIdentityPoolConfigurationException; Request ID: ecae5ba7-dc8e-****)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:731)

have any idea regarding this.

Hi @isaiahtaylor, I should expand, as my initial comment wasn't fully correct, and I shouldn't have just replied with it without investigating more:

You don't need to run amplify add auth, as amplify will create auth as part of amplify add api (if you don't have auth already) - however, you can remove all of the auth resources (and subsequently not deploy them to the cloud) if you're referencing an existing user pool:

  1. Delete backend/auth and everything under it
  2. Modify parameters.json as you've described above
  3. Modify backend-config.json to remove the top-level auth section, and update your api's authConfig as follows (remove the reference to the auth pool):
"authConfig": {
  "additionalAuthenticationProviders": [],
  "defaultAuthentication": {
    "authenticationType": "AMAZON_COGNITO_USER_POOLS"
  }
}
  1. Run amplify env checkout <environment> -> you need to do this or amplify won't pick up your changes

Viola! You can add @auth directives in your schema.graphql and everything will work as expected.

Hi @zjullion I read the whole post because amplify is a royal mess TBH and using an existing pool should be an easy feature instead of a headache, I'm on the same issue right now, I have an existing user pool that I need to use.
Following the guide I do
amplify configure
amplify init
But how do I edit the parameters? I don't have such folders unless I do an amplify add auth
What should be the correct flow of commands to run in order to get a working auth pointing at the existing pool?

Thanks for your overall help!

@dannygoncalves the answer is you don't need to. You have headed to the wrong thread. Amplify has it in its own documentation (some not so useful but written).
What you need to do is put your AWS Cognito creds in a js file (say aws-config.js) and configure amplify with it instead of the amplify generated aws-exports.js

const currentConfig = {
  Auth: {
         ......//your config, see  docs for reference
  }
}
const Amplify = require("@aws-amplify/auth");
Amplify.default.configure(currentConfig);

@Guneetgstar thanks for your reply, this thread covers the issue that I have but I could not work around it, I did that, but then when trying to run the auth method, I get an error on the console that says that I don't have an authentication setup.

@Guneetgstar thanks for your reply, this thread covers the issue that I have but I could not work around it, I did that, but then when trying to run the auth method, I get an error on the console that says that I don't have an authentication setup.

Yes because this thread covers Use existing Cognito User pool with amplify auth due to some reson/requirements which in most of the cases doesn't arise (as in your case). Hence, you just need to configure with the given implementation in amplify docs(or checkout my prev comment).

Hi - I'm closing this issue in favor of our RFC: #3977
In addition, we've already started making progress in this issue with the ability to import existing Cognito resources. Check out our launch announcement here: https://aws.amazon.com/blogs/mobile/use-existing-cognito-resources-for-your-amplify-api-storage-and-more/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

adriatikgashi picture adriatikgashi  Â·  3Comments

nason picture nason  Â·  3Comments

mwarger picture mwarger  Â·  3Comments

onlybakam picture onlybakam  Â·  3Comments

MageMasher picture MageMasher  Â·  3Comments