How to redirect after confirm amazon cognito using confirmation URL?

此生再无相见时 提交于 2019-12-03 18:58:31

问题


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.


回答1:


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"
}



回答2:


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.




回答3:


Yes, we will mark this as a feature request. However, we cannot estimate the delivery time at this point.



来源:https://stackoverflow.com/questions/47159568/how-to-redirect-after-confirm-amazon-cognito-using-confirmation-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!