Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create captcha in asp.net core Asp.net Mvc 6?

I am developing asp.net MVC 6 application in asp.net core , and i want to create a captcha for my login page. in previous .net frameworks i used the system.drawing to create a captcha but since in .net framework core we dont have system.drawing , how can i achieve this ?

one solution is to reference full .net framework but this is not what i want. i want to use the core framework.

another one is to create a project with .net framework 6 and Mvc 5 and use a web api to get the captcha image , but also this is not what i want.

is there another solution ?

like image 928
jsDevia Avatar asked May 14 '16 07:05

jsDevia


People also ask

How do you implement Captcha?

Go to the reCAPTCHA homepage and click on the Get reCAPTCHA button at the top of the screen. On the next screen, you'll find a prompt to enter a label and domain for your site, so you can identify it among your reCAPTCHA properties. Populate both fields, click on Register, and you're done.


4 Answers

I implemented Recaptcha in my ASP.NET Core apps. In my login view:

@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>

}

I implemented an extension method on controller so I can validate the captcha server side easily from any controller where I'm using it.

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

Then this snippet from the login post method in my AccountController checks the captcha server side using that extension method:

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);
    }
}

Note that to call extension methods on a controller you have to use the this keyword.

I'm using this in multiple projects currently so if you need to see more code, the most simple is in my SimpleAuth project, but I'm also using it cloudscribe

like image 90
Joe Audette Avatar answered Oct 19 '22 17:10

Joe Audette


You can do it without any special packaging. According to the recaptcha site -

Client Side Integration

Paste this snippet before the closing </head> tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js'></script>

Paste this snippet at the end of the where you want the reCAPTCHA widget to appear:

<div class="g-recaptcha" data-sitekey="YOURSITEKEY"></div>

Server Side Integration

When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:

URL: https://www.google.com/recaptcha/api/siteverify

secret (required): YOURSECRETKEY

response (required): The value of 'g-recaptcha-response'.

remoteip: The end user's ip address.

like image 40
smulholland2 Avatar answered Oct 19 '22 17:10

smulholland2


I made a wrapper for recaptcha that works with aspnetcore, check it out https://www.nuget.org/packages/PaulMiami.AspNetCore.Mvc.Recaptcha and there is some documentation at https://github.com/PaulMiami/reCAPTCHA/wiki/Getting-started

In short you need to do the following to use it:

  1. Setup the service in your your Startup class.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddRecaptcha(new RecaptchaOptions
    {
        SiteKey = Configuration["Recaptcha:SiteKey"],
        SecretKey = Configuration["Recaptcha:SecretKey"]
    });
}

2. In your "_ViewImports.cshtml" file add.

@addTagHelper *, PaulMiami.AspNetCore.Mvc.Recaptcha

3. In your view.

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

4. In your controller.

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

    return View();
}
like image 34
PaulMiami Avatar answered Oct 19 '22 16:10

PaulMiami


To easy, you can user that component, You can see how use in that link https://www.nuget.org/packages/IgniteCaptcha/1.0.0

like image 24
TheRockerDev Avatar answered Oct 19 '22 18:10

TheRockerDev