如何使用AWS Cognito在.net上使用忘记密码自定义模板?

时间:2019-11-06 11:32:55

标签: c# .net-core amazon-cognito amazon-cognito-triggers

我正在使用cognito发送自定义电子邮件以忘记密码。在哪里需要设置代码而无需触发lambda?

2 个答案:

答案 0 :(得分:3)

您唯一的选择是Lambda函数,并将其附加到用户池中的常规设置->触发器->自定义消息。

Lambda函数示例:

exports.handler = (event, context, callback) => {
    // https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html
    // dev
    if(event.userPoolId === "YOUR USER POOL ID") {
        // Identify why was this function invoked
        if(event.triggerSource === "CustomMessage_ForgotPassword") {
            if(event.request.userAttributes.locale === "fr-CA")
            {
                event.response.smsMessage = "Votre code de confirmation est: " + event.request.codeParameter;
                event.response.emailSubject = "Code de confirmation";
                event.response.emailMessage = "Votre code de confirmation: " + event.request.codeParameter + "<br/><br/>Veuillez visiter cette URL et fournir les informations demandées: ~your url~";
            }
            else
            {
                event.response.smsMessage = "Your confirmation code is: " + event.request.codeParameter;
                event.response.emailSubject = "Confirmation Code";
                event.response.emailMessage = "Your confirmation code: " + event.request.codeParameter + "<br/><br/>Please visit this url and provide the requested information: ~your url~";   
            }
        }
        // Create custom message for other events
    }
    // qa

    // prod

    // Return to Amazon Cognito
    callback(null, event);
};

答案 1 :(得分:3)

忘记密码请求:-

public async Task<Result> ForgotPassword(string email)
    {
        using (var cognito = new AmazonCognitoIdentityProviderClient(AWSConnection.AWS_AccessKey, AWSConnection.AWS_SecretKey, AWSConnection.AWSRegion))
        {
            ListUsersRequest listUsersRequest = new ListUsersRequest();
            listUsersRequest.UserPoolId = _openIdConnect.MetadataAddress.Split("/")[3];
            listUsersRequest.Filter = string.Format("email = \"{0}\"", email.ToLower()); //Get Data by Email from UserPool
            ListUsersResponse listUsersResponse = await cognito.ListUsersAsync(listUsersRequest);
            if (listUsersResponse.Users.Any())
            {
                ForgotPasswordRequest forgotPasswordRequest = new ForgotPasswordRequest();
                forgotPasswordRequest.Username = listUsersResponse.Users.Select(x => x.Username).FirstOrDefault();
                forgotPasswordRequest.ClientId = _openIdConnect.ClientId;
                ForgotPasswordResponse forgotPasswordResponse = await cognito.ForgotPasswordAsync(forgotPasswordRequest).ConfigureAwait(false);
                return Result.Execute(StatusCodes.Status200OK, GlobalMessages.FETCH_SUCCESS, forgotPasswordResponse);
            }
            else
            {
                return Result.Execute(StatusCodes.Status200OK, GlobalMessages.UserNotFound);
            }
        }
    }

触发CustomMessage_ForgotPassword Lambda:-

public RootObject FunctionHandler(RootObject input, ILambdaContext context)
    {
        string link = $"https://your-website.com/reset-password?confirmation_code=${input.request.codeParameter}&userName=${input.userName};
        var CustomMessage_ForgotPassword = string.Format("Follow this link to reset your Password.{0}", link);
        if (input.userPoolId == "YOUR USER POOL ID")
        {
            Console.WriteLine(input.userPoolId);
            if (input.triggerSource == "CustomMessage_ForgotPassword")
            {
                input.response.emailSubject = "Forgot Password";
                input.response.emailMessage = CustomMessage_ForgotPassword;
            }
        }
        return input;
    }

lambda函数中的模型:-

     public class CallerContext
    {
        public string awsSdkVersion { get; set; }
        public string clientId { get; set; }
    }

    public class UserAttributes
    {
        public string sub { get; set; }
        public string email_verified { get; set; }
        public string name { get; set; }
        public string phone_number_verified { get; set; }
        public string phone_number { get; set; }
        public string email { get; set; }
    }

    public class Request
    {
        public UserAttributes userAttributes { get; set; }
        public string codeParameter { get; set; } = "####";
        public string linkParameter { get; set; }
        public object usernameParameter { get; set; }
    }

    public class Response
    {
        public object smsMessage { get; set; }
        public object emailMessage { get; set; }
        public object emailSubject { get; set; }
    }

    public class RootObject
    {
        public string version { get; set; }
        public string region { get; set; }
        public string userPoolId { get; set; }
        public string userName { get; set; }
        public CallerContext callerContext { get; set; }
        public string triggerSource { get; set; }
        public Request request { get; set; }
        public Response response { get; set; }
    }

确认忘记密码:-

  public async Task<Result> ConfirmForgotPassword(ConfirmForgotPasswordDTO confirmForgotPasswordDTO)
    {            
        using (var cognito = new AmazonCognitoIdentityProviderClient(AWSConnection.AWS_AccessKey, AWSConnection.AWS_SecretKey, AWSConnection.AWSRegion))
        {
            ConfirmForgotPasswordRequest confirmForgotPasswordRequest = new ConfirmForgotPasswordRequest();
            confirmForgotPasswordRequest.Username = ConfirmForgotPasswordDTO.UserName;
            confirmForgotPasswordRequest.ClientId = _openIdConnect.ClientId;
            confirmForgotPasswordRequest.Password = confirmForgotPasswordDTO.Password;
            confirmForgotPasswordRequest.ConfirmationCode = confirmForgotPasswordDTO.ConfirmationCode;
            ConfirmForgotPasswordResponse confirmForgotPasswordResponse = new ConfirmForgotPasswordResponse();
            string message = string.Empty;
            try
            {
                confirmForgotPasswordResponse = await cognito.ConfirmForgotPasswordAsync(confirmForgotPasswordRequest).ConfigureAwait(false);
            }
            catch (ExpiredCodeException ex)
            {
                message = ex.Message;
            }
            catch (InvalidPasswordException ex)
            {
                message = ex.Message;
            }
            catch (Amazon.CognitoIdentityProvider.Model.LimitExceededException ex)
            {
                message = ex.Message;
            }
            catch (UserNotFoundException ex)
            {
                message = ex.Message;
            }
            catch (UserNotConfirmedException ex)
            {
                message = ex.Message;
            }
            if (confirmForgotPasswordResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                return Result.Execute(StatusCodes.Status200OK, GlobalMessages.PasswordChangedSuccessfully, confirmForgotPasswordResponse);
            }
            return Result.Execute(StatusCodes.Status400BadRequest, message);
        }
    }

确认忘记密码:-

public class ConfirmForgotPasswordDTO
    {
        public string ConfirmationCode { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }