Simple steps to achieve sliding verification code (back-end verification)

Time:2022-5-1

LazySlideCaptcha

introduce

LazySlideCaptchaIs based on Sliding verification code module of net standard 2.1. The project also provides a demonstration based on vue2Front end assemblyandBackground clipping tool
[code cloud address] | [GitHub address]

Graphic verification code, please movelazy-captcha

Online experience point here

Quick start

  1. install
Install-Package Lazy.SlideCaptcha.Core
dotnet add package Lazy.SlideCaptcha.Core
  1. Register and configure services
builder.Services.AddSlideCaptcha(builder.Configuration);

//If redis distributed cache is used
//builder.Services.AddStackExchangeRedisCache(options =>
//{
//    options.Configuration = builder.Configuration.GetConnectionString("RedisCache");
//    options.InstanceName = "captcha:";
//});
"SlideCaptcha": {
    "Backgrounds": [
      {
        "Type": "file",
        "Data": "wwwroot/images/background/1.jpg"
      },
      {
        "Type": "file",
        "Data": "wwwroot/images/background/2.jpg"
      }
    ]
  }

The required size of background picture is552 X 344, quick startDemoprojectwwwroot/images/backgroundChoose next. (for demonstration only, please make it yourself.) You can also passcrop tool Production, very simple, upload pictures, drag the range, save and generate automatically552 X 344Picture.

  1. Interface definition
[Route("api/[controller]")]
[ApiController]
public class CaptchaController : ControllerBase
{
    private readonly ICaptcha _captcha;

    public CaptchaController(ICaptcha captcha)
    {
        _captcha = captcha;
    }

    /// 
    /// id
    /// 
    /// 
    /// 
    [Route("gen")]
    [HttpGet]
    public CaptchaData Generate()
    {
        return _captcha.Generate();
    }

    /// 
    /// id
    /// 
    /// 
    /// 
    [Route("check")]
    [HttpPost]
    public bool Validate([FromQuery]string id, SlideTrack track)
    {
        return _captcha.Validate(id, track);
    }
}

So far, the back-end API service has been built.

  1. front end
    The front end provides demonstration componentslazy-slide-captcha, can be installed through NPM. For the convenience of demonstration, the demo project directly adopts the direct introduction of script.
@{
    Viewdata ["title"] = "sliding verification code";
}




    #app {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .panel {
        padding: 20px;
        box-shadow: inherit;
        border-radius: 6px;
        box-shadow: 0 0 4px 0 #999999;
        margin-top: 100px;
    }



    
        
    



@section Scripts{
    
    
    

    
        var app = new Vue({
             el: '#app',
             data(){
                return {
                    requestId: undefined,
                    failTip: '',
                    successTip: '',
                    //Width and height can be kept in the same proportion as 552 * 344
                    width: 340,
                    height: 212
                }
             },
             mounted(){
                 this.generate()
             },
             methods:{
                 generate(){
                     //Change the internal state to identify the start of the generation request
                     this.$refs.captcha.startRequestGenerate()

                     axios.get('/api/captcha/gen')
                       .then((response) => {
                           this.requestId = response.data.id
                           //Change the internal state, mark the end of the generation request, and set the background and slider image at the same time
                           this.$refs.captcha.endRequestGenerate(response.data.backgroundImage, response.data.sliderImage)
                       })
                       .catch((error) => {
                           console.log(error);
                           //Identifies the end of the build request
                           this.$refs.captcha.endRequestGenerate(null, null)
                       });
                 },
                 handleFinish(data){
                     //Change the internal state to identify the start of the authentication request
                     this.$refs.captcha.startRequestVerify()

                     axios.post(`/api/captcha/check?id=${this.requestId}`, data)
                       .then((response) => {
                           let success = response.data.result === 0
                           //Display information when validation fails
                           this. failTip = response. data. result == 1 ? ' If the verification fails, drag the slider to merge the suspended images correctly ':' verification timeout, please operate again '
                           //Display information when verification passes
                           this. Successtip = 'authentication passed, more than 80% of users'
                           //Change the internal status, identify the end of the verification request, and set the success status at the same time
                           this.$refs.captcha.endRequestVerify(success)

                           if(!success){
                                setTimeout(() => {
                                    this.generate()
                                }, 1000)
                           }
                       })
                       .catch((error) => {
                         console.log(error);
                         this. Failtip = 'service exception, please try again later'
                         //End of identity verification request
                         this.$refs.captcha.endRequestVerify(false)
                       });
                 }
             }
        });
    
}

So far, a complete sliding verification has been realized. Let’s start the service experience.

Configuration description

The configuration file and code configuration are supported. If the code configuration is configured at the same time, the code configuration overwrites the configuration file.

  • configuration file
"SlideCaptcha": {
    "Expiryseconds": 60, // cache expiration time
    "Storeagekeyprefix": "", // cache prefix
    "Tolerance": 0.02, // fault tolerance value (for verification, the notch position matches the actual sliding position, and the fault tolerance range)
    "Backgrounds": [// background image configuration
      {
        "Type": "file",
        "Data": "wwwroot/images/background/1.jpg"
      }
    ],
    //If templates is not configured, the default template is used
    "Templates": [
      {
        "Slider": {
          "Type": "file",
          "Data": "wwwroot/images/template/1/slider.png"
        },
        "Hole": {
          "Type": "file",
          "Data": "wwwroot/images/template/1/hole.png"
        }
      }
    ]
  }
  • Code configuration
builder.Services.AddSlideCaptcha(builder.Configuration, options =>
{
    options.Tolerant = 0.02f;
    options.StoreageKeyPrefix = "slider-captcha";

    options.Backgrounds.Add(new Resource(FileResourceHandler.TYPE, @"wwwroot/images/background/1.jpg"));
    options.Templates.Add
    (
        TemplatePair.Create
        (
            new Resource(FileResourceHandler.TYPE, @"wwwroot/images/template/1/slider.png"),
            new Resource(FileResourceHandler.TYPE, @"wwwroot/images/template/1/hole.png")
        )
    );
});

extend

  1. Template customization
    TemplateIt refers to the pictures used to generate grooves and drag blocks. You can set a custom template through the templates configuration node. Five by defaultTemplate(do not configure it, it has been included in the class library) as follows:
slider hole slider hole

Disable default_Template_ Call disabledefaulttemplates:

builder.Services.AddSlideCaptcha(builder.Configuration)
    .DisableDefaultTemplates();
  1. Validator customization
    Class library providesSimpleValidatorBasicValidatorTwo implementations.
    SimpleValidatorLocation verification only,BasicValidatorIn addition to the position verification, the trajectory shall be verified at the same time_BasicValidatorDue to the algorithm, it is easy to misjudge, so the class library is used by defaultSimpleValidatorAs defaultValidator
    customValidatorinheritBaseValidatorBaseValidatorProvides basic location verification.

Take a chestnut:

public class CustomValidator: BaseValidator
{
    public override bool ValidateCore(SlideTrack slideTrack, CaptchaValidateData captchaValidateData)
    {
        //Basevalidator has verified the alignment between the basic slider and the groove. Other verifications are done here

        return true;
    }
}

Replace the default validator

builder.Services.AddSlideCaptcha(builder.Configuration);
    .ReplaceValidator();
  1. Resourceprovider customization
    In addition to configuring background and template through options, you can also provide background and template in the form of customized resourceprovider.
public class CustomResourceProvider : IResourceProvider
{
    public List Backgrounds()
    {
        return Enumerable.Range(1, 10)
            .ToList()
            .Select(e => new Resource(Core.Resources.Handler.FileResourceHandler.TYPE, $"wwwroot/images/background/{e}.jpg"))
            .ToList();
    }
    
    //The customized template is returned here
    public List Templates()
    {
        return new List();
    }
}

Register resourceprovider

builder.Services.AddSlideCaptcha(builder.Configuration)
    .AddResourceProvider();
  1. Custom resourcehandler
public class UrlResourceHandler : IResourceHandler
{
    public const string Type = "url";

    public bool CanHandle(string handlerType)
    {
        return handlerType == Type;
    }

    /// 
    ///This is just a demonstration and is still read locally. Actually, it needs to be read through HTTP
    /// 
    /// 
    /// 
    /// 
    public byte[] Handle(Resource resource)
    {
        if (resource == null) throw new ArgumentNullException(nameof(resource));
        return File.ReadAllBytes(resource.Data);
    }
}

Register resourcehandler

builder.Services.AddSlideCaptcha(builder.Configuration)
    .AddResourceHandler();

Reference items

Project referencetianai-captchavue-drag-verifyExcellent project, thank you very much.

Recommended Today

JVM + GC parsing (premise knowledge concatenation)

Premise preparation JVM GC garbage collection JVM virtual machine monitoring, tuning and troubleshooting Tomcat and microservice optimization 1. Premise review 1.1. JVM memory structure 1.1.1、 JVM Architecture Overview The gray part in the figure isThread private, there is almost no garbage collectionOrange partThread sharing, the main place where garbage recycling occurs What is the class […]