Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect after confirm amazon cognito using confirmation URL?

I want to redirect to a specific url after the user confirmation in amazon cognito.

When a user sign up he will get confirmation mail with a verification link as follows https://<>.auth.us-west-2.amazoncognito.com/confirmUser?client_id=<<>>&user_name=<<>>&confirmation_code=<<>>

If the user clicks the above link it will redirect to confirmation page.

Once the user confirmation is completed the page should redirect to my application.

Please give me some idea to solve this problem.

like image 247
Richardson. M Avatar asked Nov 07 '17 13:11

Richardson. M


People also ask

What is Cognito callback URL?

A callback URL indicates where the user will be redirected after a successful sign-in. Enter Sign out URL(s). A sign-out URL indicates where your user will be redirected after signing out. Select Authorization code grant to return an authorization code that is then exchanged for user pool tokens.

How do I change my confirmation status in Cognito?

In order to change a Cognito user's status from FORCE_CHANGE_PASSWORD to CONFIRMED , we have to change their password. To change a Cognito user's password, use the admin-set-password command, setting the --permanent parameter. Copied!

How do I get a confirmation code for Cognito?

The Amazon Cognito service receives the sign-up request from the app. After verifying that the request contains all attributes required for sign-up, the service completes the sign-up process and sends a confirmation code to the user's phone (in an SMS message) or email. The code is valid for 24 hours.

How do you authenticate on Amazon Cognito?

Go to AWS Cognito service and click “Manage Identity Pools”. 2. Enter “Identity pool name”, expand the “Authentication providers” section and select “Cognito” tab. This is where the Cognito authentication provider will be registered with the Identity pool.


2 Answers

Currently, this redirection can't be done using verification link in email. I tried adding redirect_uri to the verification URL a while back but they do not work.

Workaround

  • Create an API in Api gateway which takes these 3 parameters and an additional redirect_uri parameter. In the backend lambda, make a GET request to the actual link using the parameters & confirm the user. On success, return a 302 redirect from your API using the redirect_uri as parameter.
  • In your userpool, use the custom message trigger to build a link to your API gateway api instead of the default cognito url
  • So, verification link would be something like: https://myapi.abc.com/confirm?client_id=somevalue&user_name=some_user&confirmation_code=some_code&redirect_uri=https://myapp.com
  • These values are passed to backend lambda which makes a GET request to https://your_domain.auth.us-west-2.amazoncognito.com/confirmUser?client_id=somevalue&user_name=some_user&confirmation_code=some_code

  • On success, return 302 https://myapp.com from your API Gateway

I know this is a convoluted workaround for such a simple requirement. The best way would be to raise a feature request and hope they support a redirect_uri in the Cognito URL.

EDIT

To save your lambda costs, you could also use an HTTP endpoint in your API and make a request to the cognito service endpoint for your region. Example:

POST  HTTP/1.1 Host: cognito-idp.us-east-1.amazonaws.com x-amz-target: AWSCognitoIdentityProviderService.ConfirmSignUp Content-Type: application/x-amz-json-1.1  {   "ClientId":"xxxxxxxxxxxxx",   "ConfirmationCode":"123456",   "Username":"username" } 
like image 110
agent420 Avatar answered Sep 30 '22 15:09

agent420


I got this to work with the help of above answer from @agent420 and examining the github issue https://github.com/aws-amplify/amplify-js/issues/612

So here is the complete process that I followed.

  • First we need to change the verification method to code from link since we need to grab the code when confirming the user through lambda. To do this in Cognito(AWS Console), go to Message customizations -> Verification type, change it to 'Code'.
  • Next we will be adding a lambda trigger to be fired before sending the email verification. To add a lambda for this go to Lambda(AWS Console) and Create a function. Given below is the lambda I used.

exports.handler = (event, context, callback) => {      // Identify why was this function invoked      if(event.triggerSource === "CustomMessage_SignUp") {          console.log('function triggered');          console.log(event);          // Ensure that your message contains event.request.codeParameter. This is the placeholder for code that will be sent          const { codeParameter } = event.request          const { userName, region } = event          const { clientId } = event.callerContext          const { email } = event.request.userAttributes          const url = 'https://example.com/api/dev/user/confirm'          const link = `<a href="${url}?code=${codeParameter}&username=${userName}&clientId=${clientId}&region=${region}&email=${email}" target="_blank">here</a>`          event.response.emailSubject = "Your verification link"; // event.request.codeParameter          event.response.emailMessage = `Thank you for signing up. Click ${link} to verify your email.`;      }        // Return to Amazon Cognito      callback(null, event);  };

Your email will be sent with the subject and message specified in event.response.emailSubject and event.response.emailMessage. The user will directed to the url specified in the url variable.

  • To add the trigger Go to, Cognito(Aws-console) Triggers -> Custom message and select the lambda you just created.
  • Since the user will directing to our url we can control the request, confirm the user and redirect to a url of your choice.

I used a lambda for this with the use of AWS APIGateway. Given below is the code I wrote in nodejs where I used a 301 redirect.

'use strict';  var AWS = require('aws-sdk');  AWS.config.setPromisesDependency(require('bluebird'));  var CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region: process.env.REGION });    module.exports.verifyEmailAddress = (req, context, callback) => {      console.log('req');    console.log(req);    const confirmationCode = req.queryStringParameters.code    const username = req.queryStringParameters.username    const clientId = req.queryStringParameters.clientId    const region = req.queryStringParameters.region    const email = req.queryStringParameters.email      let params = {      ClientId: clientId,      ConfirmationCode: confirmationCode,      Username: username    }      var confirmSignUp = CognitoIdentityServiceProvider.confirmSignUp(params).promise()      confirmSignUp.then(      (data) => {        let redirectUrl = process.env.POST_REGISTRATION_VERIFICATION_REDIRECT_URL;        const response = {          statusCode: 301,          headers: {            Location: redirectUrl,          }        };              return callback(null, response);      }    ).catch(      (error) => {        callback(error)      }    )  }

Replace environmental variables REGION and POST_REGISTRATION_VERIFICATION_REDIRECT_URL with the values of yours according to the requirement.

like image 23
Yasith Prabuddhaka Avatar answered Sep 30 '22 14:09

Yasith Prabuddhaka