如何在asp.net核心Asp.net Mvc 6中创建验证码?

时间:2016-05-14 07:21:47

标签: asp.net-mvc asp.net-core asp.net-core-mvc captcha

我正在asp.net核心开发asp.net MVC 6应用程序,我想为我的登录页面创建一个验证码。在以前的.net框架中,我使用system.drawing来创建验证码但是因为在.net框架核心中我们没有system.drawing,我怎么能实现这个呢?

一个解决方案是引用完整的.net框架,但这不是我想要的。我想使用核心框架。

另一个是使用.net framework 6和Mvc 5创建一个项目并使用web api来获取验证码图像,但这也不是我想要的。

还有另一种解决方案吗?

5 个答案:

答案 0 :(得分:8)

我为aspnetcore制作了一个recrapcha包装器,请查看https://www.nuget.org/packages/PaulMiami.AspNetCore.Mvc.Recaptcha并在https://github.com/PaulMiami/reCAPTCHA/wiki/Getting-started

上找到一些文档

简而言之,您需要执行以下操作才能使用它:

  1. 在您的Startup类中设置服务。
  2. public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    
        services.AddRecaptcha(new RecaptchaOptions
        {
            SiteKey = Configuration["Recaptcha:SiteKey"],
            SecretKey = Configuration["Recaptcha:SecretKey"]
        });
    }
    

    2。在你的" _ViewImports.cshtml"文件添加。

    @addTagHelper *, PaulMiami.AspNetCore.Mvc.Recaptcha
    

    3。在你看来。

    <form asp-controller="Home" asp-action="Index" method="post">
        <recaptcha />
        <input type="submit" value="submit" />
    </form>
    @section Scripts {
        <recaptcha-script />
    }
    

    4。在你的控制器中。

    [ValidateRecaptcha]
    [HttpPost]
    public IActionResult Index(YourViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            return new OkResult();
        }
    
        return View();
    }
    

答案 1 :(得分:7)

我在ASP.NET核心应用程序中实现了Recaptcha。在我的登录视图中:

@if (Model.RecaptchaSiteKey.Length > 0)
{
    <script src='https://www.google.com/recaptcha/api.js'></script>
}


@if (Model.RecaptchaSiteKey.Length > 0)
{
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <div class="g-recaptcha" data-sitekey="@Model.RecaptchaSiteKey"></div>
            @Html.ValidationMessage("recaptchaerror", new { @class = "text-danger" })
        </div>
    </div>

}

我在控制器上实现了扩展方法,因此我可以从我正在使用它的任何控制器轻松验证验证码服务器端。

public static async Task<RecaptchaResponse> ValidateRecaptcha(
    this Controller controller,
    HttpRequest request,
    string secretKey)
{
    var response = request.Form["g-recaptcha-response"];
    var client = new HttpClient();
    string result = await client.GetStringAsync(
        string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
            secretKey,
            response)
            );

    var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(result);

    return captchaResponse;
}

然后我的AccountController中的login post方法的这个片段使用该扩展方法检查验证码服务器端:

if ((Site.CaptchaOnLogin) && (Site.RecaptchaPublicKey.Length > 0))
{
    var recpatchaSecretKey = Site.RecaptchaPrivateKey;
    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

    if (!captchaResponse.Success)
    {
        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
        return View(model);
    }
}

请注意,要在控制器上调用扩展方法,您必须使用this关键字。

我目前在多个项目中使用它,所以如果你需要查看更多代码,最简单的是在我的SimpleAuth项目中,但我也在使用它cloudscribe

答案 2 :(得分:0)

请按照以下步骤在Mvc中创建Captcha。

  1. 将CaptchaMvc库添加到应用程序中的参考层,如下所示。

  2. 现在像这样创建索引视图。

  3. 查看

     @using CaptchaMvc.HtmlHelpers  
     @using MathCaptcha;  
     @using CaptchaMvc;  
    
     @using (Html.BeginForm()) {  
     @Html.ValidationSummary(true)  
    
    <fieldset>  
        <legend>Captcha Example</legend>  
    
        @Html.MathCaptcha()  
    
        @*@Html.Captcha(3)*@  
    
        <input type="submit" value="Send" />  
    
     </fieldset>  
     }  
    

    @ Html.MathCaptcha()辅助类然后它将生成一个数学CAPTCHA。如果您使用@Html。 Captcha(3)helper类然后它将生成Char CAPTCHA。 3是CAPTCHA的长度。

    1. 在post action方法中,我为CAPTCHA验证编写了代码。

       [HttpPost]  
       public ActionResult Index(string empty)  
       {  
          // Code to validate the CAPTCHA image
          if (this.IsCaptchaValid("Captcha not valid"))  
          {  
      
              // do your stuff  
          }  
      
          return View();  
       }  
      

答案 3 :(得分:0)

为方便起见,您可以使用该组件,您可以在该链接中查看如何使用 https://www.nuget.org/packages/IgniteCaptcha/1.0.0

答案 4 :(得分:0)

我已经做到了:

添加对System.Drawing.Common的引用

如果在linux上安装linux库:

sudo apt install libc6-dev
sudo apt install libgdiplus
  1. 在AccountController中
        [AllowAnonymous]
        public async Task<IActionResult> GetCaptchaImage()
        {
            var validate = "";
            var bmp = ImageCaptcha.Generate(200, 150, out validate);

            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(ms.ToArray());
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                SetCookie("CV", validate.Hash()+"");
                return File(ms.ToArray(),"image/png");
            }
        }

        // move to base controller
        public void SetCookie(string key, string value, int? expireTime = null)
        {
            CookieOptions option = new CookieOptions();

            if (expireTime.HasValue)
                option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
            else
                option.Expires = DateTime.Now.AddMilliseconds(5 * 60 * 1000);

            Response.Cookies.Append(key, value, option);
        }


将此类添加到项目中-在内存中生成随机旋转的字母bmp:

public static class ImageCaptcha
    {

        public static Bitmap Generate(int w, int h, out string validate)
        {
            Bitmap bmp = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            Graphics graphics = Graphics.FromImage(bmp);
            var brush = new[] { Brushes.Brown, Brushes.LawnGreen, Brushes.Blue, Brushes.Coral};
            var rand = new Random((int)DateTime.Now.Ticks);
            validate = null;
            using (Graphics g = Graphics.FromImage(bmp))
            {
                for (int i = 0; i < 4; i++)
                {
                    var text = Convert.ToChar( rand.Next(97, 122)).ToString();
                    validate += text;
                    if(i==0) g.TranslateTransform(bmp.Width / 2, bmp.Height / 2);
                    g.RotateTransform(40 * 5 * rand.Next(1, 6));
                    var font = new Font("Arial", h * 0.25f + 8 * rand.Next(1, 6), FontStyle.Bold);
                    SizeF textSize = g.MeasureString(text, font);
                    g.DrawString(text, font, brush[i],15*(i+1) -(textSize.Width / 2), -(textSize.Height / 2));
                }
            }

            return bmp;
        }

    }

添加此实用程序类可轻松实现md5哈希:

public static partial class H
{
    public static int Hash(this string value)
    {
        MD5 md5Hasher = MD5.Create();
        var hashed = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(value));
        var ivalue = BitConverter.ToInt32(hashed, 0);
        return ivalue;
    }
}
  1. 将“注册操作”更改为此,请参阅注释-添加,更改:
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            var validCaptchaText = Request.Cookies["cv"]; //added
            if (ModelState.IsValid && model.UserCaptchaText.Hash()+""==validCaptchaText) //changed
            {
                var user = new AppUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation("User created a new account with password.");
                    return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
  1. 在“ ConfirmPassword”之后的注册视图中
                <div class="form-group">
                    <label>Captcha</label><br />
                    <img style="width:100%; border:solid 1px #ced4da" height="150" src="@Url.Action("GetCaptchaImage")" />
                    <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
                    <ul style="list-style-type:none">
                        <li style="width:24px;height:12px; display:inline-block; background-color:#a52a2a "></li>
                        <li style="width:24px;height:12px; display:inline-block; background-color:#7cfc00 "></li>
                        <li style="width:24px;height:12px; display:inline-block; background-color:#0000ff "></li>
                        <li style="width:24px;height:12px; display:inline-block; background-color:#ff7f50 "></li>
                    </ul>
                </div>

                <div class="form-group">
                    <label asp-for="UserCaptchaText"></label>
                    <input asp-for="UserCaptchaText" class="form-control" />
                </div>

                <button style="color:white; background-color:#4a7dbc" type="submit" class="btn btn-default">Register</button>

完成。