By using AWS re:Post, you agree to the Terms of Use
/Amazon Cognito/

Questions tagged with Amazon Cognito

Sort by most recent
  • 1
  • 90 / page

Browse through the questions and answers listed below or filter and sort to narrow down your results.

Amplify Custom Subscription VTL

I am trying to provide multitenancy checks in a VTL that runs as part of a custom subscription. I am using the `@function` and `@aws_subscribe` annotations; the `@function` references an amplify function I added using `amplify add function`, naming it `perfectQueuePortalReceiveOrder` . Here are excerpts from my `schema.graphql`: ``` type ReceiveOrderResponse { brandSlug: String! @aws_iam @aws_cognito_user_pools(cognito_groups: ["perfectCoAdmin", "tablet"]) storeNumber: String! @aws_iam @aws_cognito_user_pools(cognito_groups: ["perfectCoAdmin", "tablet"]) orderDetails: String! @aws_iam @aws_cognito_user_pools(cognito_groups: ["perfectCoAdmin", "tablet"]) } type Mutation { receiveOrder(brandSlug: String!, storeNumber: String!, orderDetails: String!): ReceiveOrderResponse @function(name: "perfectQueuePortalReceiveOrder-${env}") @aws_iam @aws_cognito_user_pools(cognito_groups: ["perfectCoAdmin"]) } type Subscription { onReceiveOrder(brandSlug: String!, storeNumber: String!): ReceiveOrderResponse @aws_subscribe(mutations: ["receiveOrder"]) @aws_cognito_user_pools(cognito_groups: ["perfectCoAdmin", "tablet"]) } ``` The issue is that it does not appear that any VTL templates are generated for the Subscription. After issuing `amplify api gql-compile`, I see in the `build/resolvers` directory that VTL resolvers were generated both for the mutation, `Mutation.receiveOrder.res.vtl` as well as the lambda request/response templates: `InvokePerfectQueuePortalReceiveOrderLambdaDataSource.req.vtl` `InvokePerfectQueuePortalReceiveOrderLambdaDataSource.res.vtl`. However, _no_ `Subscription.onReceiveOrder.*` VTL template gets generated at all. My goal is simply to override the VTL template _only for the subscription_, in order to compare custom cognito user attributes against the arguments provided to the subscription, and give an unauthorized error if the arguments do not match the identity claims. But no VTL templates seem to get generated for the subscription; only for the mutation. How can I compare the arguments to a custom Subscription that is `@aws_subscribe`d to a custom Mutation, itself using `@function`, against the cognito-based identity claims provided in the $ctx during VTL processing for _the initiation of the subscription_? What is particularly confusing is that everywhere else I have used the `@aws_cognito_user_pools` and `@aws_iam` tags, the results have appeared in the build/resolvers VTL templates. _But not for subscriptions_. Why not? Strangely, these annotations _do_ seem to be honored, however, I cannot find any VTL code that implements that honoring, as I can with Queries and Mutations. Help?
0
answers
0
votes
15
views
asked 7 days ago

How do I change the expiration time of credential information retrieved from the Cognito ID Pool?

We are using aws-sdk to get temporary credential information from the Cognito ID pool in order to send requests from our front-end web application to the API Gateway that has been configured for authorization by the IAM authorizer. The credential information expiration time is 1 hour by default, is there any way to change the expiration time? ``` const client = new CognitoIdentityClient({ region: process.env.VUE_APP_AWS_REGION }); const getIdCommandInput = { AccountId: process.env.VUE_APP_AWS_ACCOUNT_ID, IdentityPoolId: process.env.VUE_APP_COGNITO_AUTH_IDENTITY_POOL_ID, Logins: {} }; const userPool = `cognito-idp.${process.env.VUE_APP_AWS_REGION}.amazonaws.com/${process.env.VUE_APP_COGNITO_AUTH_USER_POOL_ID}`; getIdCommandInput.Logins[userPool] = store.state.authenticateResult.idToken; const getIdCommand = new GetIdCommand(getIdCommandInput); const identityIdResponse = await client.send(getIdCommand); const getCredentialsForIdentityCommandInput = { IdentityId: identityIdResponse.IdentityId, Logins: {} }; getCredentialsForIdentityCommandInput.Logins[userPool] = store.state.authenticateResult.idToken; const getCredentialsForIdentityCommand = new GetCredentialsForIdentityCommand(getCredentialsForIdentityCommandInput); const credentialsResponse = await client.send(getCredentialsForIdentityCommand); ``` When the credential information is retrieved with the above code, the Expiration property contains the date and time one hour later. I tried the following, but there was no change in the 1-hour expiration. (1) Change the "maximum session time" of IAM roles set to "authenticated roles" in the Cognito identity pool to 2 hours. (2) Change the "Maximum session time" of IAM roles set to groups in the Cognito user pool to 2 hours.
1
answers
0
votes
40
views
asked 9 days ago

Cognito logout endpoint doesn't support options, so how can CORS preflight work?

Hi, I am having issues getting my spring security OAuth Client test project to logout a user from Cognito. Background Information: I have a Java Spring test project set up to get familiar with Authentication using OAuth / OIDC with Cognito. It is based on this tutorial: https://spring.io/guides/tutorials/spring-boot-oauth2/ I have a Cognito User Pool set up with appropriate API Client settings for "Authorization code grant" flow. This works very well except I wanted to logout from Cognito as well as Spring session, as I want to be able to login as another user. So I then added a LogoutSuccessHandler to my spring config to cause a redirect to the Cognito logout end point. It was done as shown here: https://rieckpil.de/oidc-logout-with-aws-cognito-and-spring-security/ Apparently this has worked for some people. The problem: It largely works. My Spring session is invalidated, and logout returns a redirect to the browser to Cognito Logout endpoint along with what I believe to be the correct parameters. However the browser (same for Firefox and Chrome) then makes a preflight Cors call to the Cognito logout end point and this will result in a 404 as "OPTIONS" is not supported on the end point. Example: 1. Request to my application to logout: URL GET to http://localhost:8080/logout With session cookie etc 2. My test service response Redirect to: Location: https://cortexo.auth.eu-west-2.amazoncognito.com/logout?client_id=<ClientId>&logout_uri=http://localhost:8080 Relevant response headers (yes they are very stupidly open for testing): Access-Control-Allow-Headers: Content-type,responseType Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS Access-Control-Allow-Origin: * Access-Control-Max-Age: 3600 If I manually browse to this redirected URL (copy and paste into browser bar) then Cognito will logout and redirect back to my project as expected. However the browser when following the redirect, first attempts to do a Cors preflight check to the URL by calling with an OPTIONS call. This results in a browser reported error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I believe the reason for this is that if you do an OPTIONS call to the Logout end point it will result in a 404 (not found) error and the end point documentation confirms that only GET is supported. The questions are: 1. I'm curious as to why the tutorial for Spring OAuth logout has worked for some others 2. Is this approach the right one? Am I missing something? 3. Any suggestions on how I can I work around this (still using Spring Security OAuth Client, as Spring Security is what we are using in our real projects)? Thanks
1
answers
0
votes
38
views
asked 9 days ago

Cognito Login With Amazon "Token is not from a supported provider of this identity pool." error using JavaScript LWA

I have a Login With Amazon (LWA) button on a web page of mine, [Configurations](https://developer.amazon.com/loginwithamazon/console/site/lwa/overview.html) shows "Client ID:amzn1.application-oa2-client.87d..." [LWA SDK for Javascript](https://developer.amazon.com/docs/login-with-amazon/install-sdk-javascript.html) is configured as specified in the link. I can click the button and click to allow on the popup, and I am redirected back to the landing page with a URL `https://[my/site]?success=null&access_token=Atza...&token_type=bearer&expires_in=3600&scope=profile` So far so good. On that page, I import the AWS SDK, decode the access token URI component, and attempt to get credentials from the Amazon Cognito provider ``` // Initialize the Amazon Cognito credentials provider AWS.config.region = 'us-east-1'; // Region AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'us-east-1:09...REDACTED...30', Logins: {'www.amazon.com': accesstoken } }); AWS.config.credentials.get((e) => console.log(e,AWS.config.credentials)); ``` which simply returns `NotAuthorizedException: Token is not from a supported provider of this identity pool.` from what developer tools shows is a POST to `https://cognito-identity.us-east-1.amazonaws.com/` with payload `{"IdentityPoolId":"us-east-1:09...REDACTED...30","Logins":{"www.amazon.com":"Atza|Iw..."}}` The Cognito/federated identities identity pool dashboard at `https://us-east-1.console.aws.amazon.com/cognito/pool/edit/?region=us-east-1&id=us-east-1:09...REDACTED...30` shows under "Authentication providers" Amazon App ID `amzn1.application-oa2-client.87d...` and under "Authenticated role selection" is "Choose role with rules" where the only rule has claim "email" "Contains" "@redacted.my.domain" is then applied the authenticated role with a default "Role resolution" of DENY. Edit: I have also tried setting "Role resolution" to "Use default Authenticated role" and the same error persists. Edit 2: I have tried changing the Logins portion of the payload to `Logins: {'www.amazon.com': 'amzn1.application-oa2-client.87d...' }` which results in `NotAuthorizedException: Invalid login token.` I'm pretty sure that's wrong since using the app ID for the token wouldn't be specific to a user but I tried it anyway since some github code did. Most github code seems to use the access token. What is going wrong here? Why won't Cognito accept the Login With Amazon access token?
1
answers
0
votes
32
views
asked 12 days ago

Cognito Migration Trigger errors when Lambda execution time too high

I am currently in the process of validating the migration of a set of users to a cognito user pool via the migration trigger, the essence of the lambda function for the trigger can be boiled down to: ``` def lambda_handler(event, context): response = requests.post(external_auth_api_url, json_with_user_and_pass) if response.status_code = 200: event["response"] = { "userAttributes": { "username": event["userName"], "email": event["userName"], "email_verified": "true" }, "finalUserStatus": "CONFIRMED", "messageAction": "SUPPRESS" } return event ``` This is doing an external rest call to the old system the user was signing in through as per the documentation and returning a success response. The issue I noticed is that if the lambda function time is too long, for example, the average execution time of this lambda for me right now via ngrok is about 5 seconds total, cognito is failing when I call initiateAuth with USERNAME_PASSWORD flow and returning the following: ``` botocore.errorfactory.UserNotFoundException: An error occurred (UserNotFoundException) when calling the InitiateAuth operation: Exception migrating user in app client xxxxxxxxxxxx ``` I managed to validate that this issue was occurring by simply returning a success response without doing an external REST call and essentially bringing the lambda function runtime down to milliseconds, in which case I got the tokens as expected and the user was successfully migrated. I also tested this by simply having a lambda function like: ``` def lambda_handler(event, context): time.sleep(5) event["response"] = { "userAttributes": { "username": event["userName"], "email": event["userName"], "email_verified": "true" }, "finalUserStatus": "CONFIRMED", "messageAction": "SUPPRESS" } return event ``` This fails with the same error response as above. If anyone can advise, I am not sure if there is a maximum time the migration trigger will wait that is not documented, I wouldn't expected the trigger to have such a thing if the migration trigger's intention is to do external REST calls which may or may not be slow. Thanks in advance!
1
answers
2
votes
19
views
asked 14 days ago

Cognito Hosted Login Page Redirects to /error when multiple Sign In windows are open

I'm using the Cognito hosted login page to authenticate into my application. The response_type is code and I'm generating a login url that includes the following query parameters: client_id, redirect_uri, response_type, scope and state. Under a specific set of circumstances, when clicking Sign In on the log in page, it will 302 Redirect to `[my-app].[my-region].amazoncognito.com/error` (note there's no query string) with a 400 Response Code. Typically clicking Sign In will navigate to my callback page where the authentication is completed, but in this instance it never hits anything in my application, it redirects from Amazon to Amazon. This is the specific sequence in order to reproduce: - Navigate to the application and sign in, then sign out. You should be redirected to a screen with a button that says "Sign In as [email address]" (Not the screen with fields for username and password. This does not seem to occur when that screen is used to log in). - Before clicking the Sign in button, copy the URL, and navigate to the same URL in a new tab or window. - In that window, click the Sign In button. - Go back to the original window - Click the Sign In button - You will get a 302 Redirect to the `[my-app].[my-region].amazoncognito.com/error` page I've tried logging locally in my application, but like I said it never hits anything on my side. If there is logging on the AWS side, I don't know where to look. Please let me know if this is a known issue, if there is a solution, or if any more information is needed. Thanks in advance
1
answers
0
votes
24
views
asked 21 days ago

Cognito "confirmDevice" error: "Invalid device credentials given"

I have a Cognito User Pool working with MFA enabled (optional), and I am currently working on setting up Device Tracking so that users can bypass MFA for trusted devices ("Allow users to bypass MFA for trusted devices" set to "Yes"). I am using the AWS SDK for **Ruby**, and can successfully step through the `admin_initiate_auth` and `admin_respond_to_auth_challenge` steps. When I run `confirm_device` I am getting an exception: ``` Invalid device credentials given, no credentials given ``` Searching on Google for the exception message, I've so far been unable to find any examples of error message for Cognito. The code I'm using: ```ruby class Cognito attr_reader :client, :user_pool_id, :app_client_id, :app_client_secret def initialize @client = Aws::CognitoIdentityProvider::Client.new( region: ENV['AWS_REGION'], access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'] ) @user_pool_id = ENV['AWS_USER_POOL_ID'] @app_client_id = ENV["AWS_APP_CLIENT_ID"] @app_client_secret = ENV["AWS_APP_CLIENT_SECRET_KEY"] end class << self def secret_hash(username) cognito = self.new Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', cognito.app_client_secret, username + cognito.app_client_id)) end def authenticate(username:, password:) cognito = self.new user_object = { USERNAME: username, PASSWORD: password, SECRET_HASH: Cognito.secret_hash(username), } auth_object = { user_pool_id: cognito.user_pool_id, client_id: cognito.app_client_id, auth_flow: "ADMIN_NO_SRP_AUTH", auth_parameters: user_object, } cognito.client.admin_initiate_auth(auth_object) end def admin_respond_to_auth_challenge(session:, mfa_code:, username:) cognito = self.new cognito.client.admin_respond_to_auth_challenge({ user_pool_id: cognito.user_pool_id, client_id: cognito.app_client_id, challenge_name: "SMS_MFA", # required, accepts SMS_MFA, SOFTWARE_TOKEN_MFA, SELECT_MFA_TYPE, MFA_SETUP, PASSWORD_VERIFIER, CUSTOM_CHALLENGE, DEVICE_SRP_AUTH, DEVICE_PASSWORD_VERIFIER, ADMIN_NO_SRP_AUTH, NEW_PASSWORD_REQUIRED challenge_responses: { "SMS_MFA_CODE" => mfa_code, "USERNAME" => username, "SECRET_HASH" => Cognito.secret_hash(username), }, session: session, context_data: { # TODO get these from request. ip_address: "127.0.0.1", # required server_name: "localhost", # required server_path: "https://127.0.0.1/", # required http_headers: [ # required { header_name: "StringType", header_value: "StringType", }, ], }, }) end def confirm_device(device_key:, access_token:, device_name: nil) cognito = self.new cognito.client.confirm_device({ device_key: device_key, access_token: access_token, device_name: device_name, }) end end end ``` And called with: ``` r = Cognito.authenticate(username: 'user.email@gmail.com', password: "Password1") challenge = Cognito.admin_respond_to_auth_challenge(session: r.session, mfa_code: "123456", username: 'user.email@gmail.com') confirm = Cognito.confirm_device(device_key: challenge.authentication_result.new_device_metadata.device_key, access_token: challenge.authentication_result.access_token, device_name: "John's Machine") ``` With the full error being: ``` /Users/myname/.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/aws-sdk-core-3.126.0/lib/seahorse/client/plugins/raise_response_errors.rb:17:in `call': Invalid device credentials given, no credentials given (Aws::CognitoIdentityProvider::Errors::InvalidParameterException) ``` I'm not sure what credentials I'm missing. Any help would be appreciated! Thank you.
0
answers
0
votes
20
views
asked a month ago

Simple Amplify Storage Requests Which Require Authentication

Hello, I am new to AWS, and I am using Amplify to build my application (React + Node). I am trying to make a very simple storage interface for user documents, and I don't want these documents to be accessible by those who do not sign in through the Cognito user pool. However, I do want these documents to be accessible to all users who have signed in through my application. I followed all of the directions specified in [the official documentation page regarding setup](https://docs.amplify.aws/lib/storage/getting-started/q/platform/js/#storage-with-amplify), and didn't configure any special options. I then went into the web interface for my S3 bucket, found the newly created storage bucket, and added a folder called "templates" with a couple sub folders, and then some user document templates. The problems started to occur upon calling the `Storage.list(...)` function within my application. The promise would resolve successfully, but the list would be empty. I understand now that's because my application was attempting to index the S3 bucket through a `public` scope prefix. When I create a folder named public, and add the files in there, everything works nicely. I was under the opinion though that using this public folder would allow my privileged content to be indexed to users who were not credentialed (i.e. guests from outside my application who didn't pass through the Cognito login portal). Is that the case? There are no groups configured from within my Cognito user pool. Right now, calling Amplify storage API functions work, but only in the `public` scope. I had thought what I wanted to do was only allow such functionality within the `private` scope; but I'm beginning to think based on the docs pages regarding user access that what I would be fine using the `public` scope, as it doesn't allow access to internal files by guests, who would not be signed in. This hunch is furthered by information regarding `protected` and `private` scopes being user-specific. Should I delve deeper into the permissions associated with these bucket objects, and configure some sort of user group system and then configure ACLs based on the groups, or would using files within the public scope be fine for my use case? I just don't want users who aren't signed in through Cognito to be able to access files. Thank you for your time, and I hope this question finds you well.
0
answers
0
votes
18
views
asked a month ago

I'd like to request to S3 as a cognito certification qualification.

I'd like to request to S3 as a cognito certification qualification. S3 is using sdk Cognito is using amplify. Use an angular typescript. I would like to replace the secret key with the cognito authentication information when creating S3. I want to access s3 with the user I received from Auth.signIn, but the credentials are missing. I need your help. ``` public signIn(user: IUser): Promise<any> { return Auth.signIn(user.email, user.password).then((user) => { AWS.config.region = 'ap-northeast-2'; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'ap-northeast-2:aaaaaaaa-bbbb-dddd-eeee-ffffffff', }); const userSession = Auth.userSession(user); const idToken = userSession['__zone_symbol__value']['idToken']['jwtToken']; AWS.config.region = 'ap-northeast-2'; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'ap-northeast-2:aaaaaaaa-bbbb-dddd-eeee-ffffffff', RoleArn: 'arn:aws:iam::111111111111:role/Cognito_role', Logins: { CognitoIdentityPool: 'ap-northeast-2:aaaaaaaa-bbbb-dddd-eeee-ffffffff', idToken: idToken, }, })); const s3 = new AWS.S3({ apiVersion: '2012-10-17', region: 'ap-northeast-2', params: { Bucket: 'Bucketname', }, }); s3.config.credentials.sessionToken = user.signInUserSession['accessToken']['jwtToken']; s3.listObjects(function (err, data) { if (err) { return alert( 'There was an error: ' + err.message ); } else { console.log('***********s3List***********', data); } }); } ``` bucket policy ``` { "Version": "2012-10-17", "Id": "Policy", "Statement": [ { "Sid": "AllowIPmix", "Effect": "Allow", "Principal": "*", "Action": "*", "Resource": "arn:aws:s3:::s3name/*", } ] } ``` cognito Role Policies - AmazonS3FullAccess ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:*", ], "Resource": "*" } ] } ```
0
answers
0
votes
7
views
asked 2 months ago

Access S3 files from Unity for mobile development

I'm trying to configure the AWS S3 service to download the included files in a bucket using Unity for mobile. I downloaded the SDK package and I got it installed. From AWS console I set up a IAM policy and roles for unauth users I created a Cognito IdentityPool and got the relative id I set up the S3 bucket and its policy using the generator, including the **arn:aws:iam::{id}:role/{cognito unauth role}** and the resource **arn:aws:s3:::{bucket name}/***. In code I set credentials and region and create CognitoAWSCredentials (C# used) ```C# _credentials = new CognitoAWSCredentials(IdentityPoolId, _CognitoIdentityRegion); ``` then I create the client: ```C# _s3Client = new AmazonS3Client(_credentials, RegionEndpoint.EUCentral1); // the region is the same in _CognitoIdentityRegion ``` I then try to use the s3Client to get my files (in bucketname subfolders) ``` private void GetAWSObject(string S3BucketName, string folder, string sampleFileName, IAmazonS3 s3Client) { string message = string.Format("fetching {0} from bucket {1}", sampleFileName, S3BucketName); Debug.LogWarning(message); s3Client.GetObjectAsync(S3BucketName, folder + "/" + sampleFileName, (responseObj) => { var response = responseObj.Response; if (response.ResponseStream != null) { string path = Application.persistentDataPath + "/" + folder + "/" + sampleFileName; Debug.LogWarning("\nDownload path AWS: " + path); using (var fs = System.IO.File.Create(path)) { byte[] buffer = new byte[81920]; int count; while ((count = response.ResponseStream.Read(buffer, 0, buffer.Length)) != 0) fs.Write(buffer, 0, count); fs.Flush(); } } else { Debug.LogWarning("-----> response.ResponseStream is null"); } }); } ``` At this point I cannot debug into the Async method, I don't get any kind of error, I don't get any file downloaded and I even cannot check is connection to AWS S3 has worked in some part of the script. What am I doing wrong? Thanks for help a lot!
0
answers
0
votes
4
views
asked 3 months ago
  • 1
  • 90 / page