Skip to content

Latest commit

 

History

History
81 lines (63 loc) · 1.86 KB

session-sms.md

File metadata and controls

81 lines (63 loc) · 1.86 KB

Email captcha base session

  1. Install the required nuget package

        Install-Package NCaptcha.AspNetCore.SessionSms
        Install-Package NCaptcha.Targets.Sms.Aliyun
  2. Add Options in the appsettings.json file. It depends on which SMS service you choose.

    "CaptchaAliyunSms": {
        "AccountKeyId": "",
        "AccessKeySecret": "",
        "SmsServiceSignName": "",
        "SmsServiceTemplateCode": ""
    }
  3. Register in DI

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession();
        services.AddSessionBasedSmsCaptcha(builder =>
            builder.UseAliyunSmsCaptcha(Configuration.GetSection("CaptchaAliyunSms").Bind);
        );
    }
  4. Configure the session

    public void Configure(IApplicationBuilder app)
    {
        app.UseSession();
    }
  5. Add a API for sending captcha code

    public class LoginModel : PageModel
    {
        private readonly ICaptchaGenerator _captchaGenerator;
    
        public LoginModel(ICaptchaGenerator captchaGenerator)
        {
            _captchaGenerator = captchaGenerator;
        }
    
        public async Task OnPostSendCaptchaAsync() => await _captchaGenerator.GenerateCaptchaAsync();
    }
  6. Validate the captcha

    public class LoginModel : PageModel
    {
        private readonly ICaptchaValidator _captchaValidator;
    
        public LoginModel(ICaptchaValidator captchaValidator)
        {
            _captchaValidator = captchaValidator;
        }
    
        public async Task<IActionResult> OnPostAsync()
        {
            if (!await _captchaValidator.ValidateAsync(Input.Captcha))
            {
                ModelState.AddModelError(nameof(InputModel.Captcha), "Invalid captcha.");
                return Page();
            }
        }
    }