一款小而美的开源滑动验证码组件

科技趣谈有前端 2024-03-05 08:49:50

往期精彩:

首发: 趣谈前端公众号

hi, 大家好, 我是徐小夕, 今天给大家分享一款非常有意思的开源组件, 可以实现我们平时开发中的滑动验证码需求, 当然也是技术圈小伙伴奋战了无数个黑夜和白天的结果, 值得好好推荐一下.

react-rotate-captcha 是一款开箱即用的滑动验证码 React 组件,基于 isszz/rotate-captcha 做的二次开发;结合了腾讯防水墙,增加安全策略.

具体策略由两部分组成:

policie默认策略rules策略组规则

策略规则:

limit: 上限次数,达到峰值后重新验证,0不限制time: 使用期限,过期后重新验证,0不限制routers: 匹配要授权的路由组,null全匹配

这里的路由是指验证通过后,要执行操作的路由,而不是验证操作时的路由

原理:

验证通过后将颁发:sid、ticket执行操作时验证决定是否通过,通过就去和执行的route进行匹配从而避免跨权,跨范围执行

优点:

针对不同应用场景提供验证例如登录验证有效期30分钟,后台操作按次数进行身份验证

后端提供 Laravel 扩展:levi/laravel-rotate-captcha ,可直接使用或根据 Api 接口定制.

效果如下:

设计思路

具体的使用安装方式如下:

// yarn安装yarn add react-rotate-captcha// pnpm安装pnpm add react-rotate-captcha

使用方式如下:

// 1. 通过status唤起import { useState } from 'react';import RotateCaptcha from "react-rotate-captcha";function App() { const [open, setOpen] = useState(true); return <RotateCaptcha open={open} onClose={() => setOpen(false)} />}// 2. 通过Instance唤起import RotateCaptcha from "react-rotate-captcha";function Page() { const captcha = RotateCaptcha.useCaptchaInstance(); return ( <button onClick={() => captcha.open()}>click it</button> );}function App() { return ( <RotateCaptcha> <Page /> </RotateCaptcha> );}

当然我们也可以使用 ref 来实现同样的效果:

import { useRef } from 'react';import RotateCaptcha, { CaptchaInstance } from "react-rotate-captcha";function App() { const ref = useRef<CaptchaInstance>(null); return ( <RotateCaptcha ref={ref}> <button onClick={() => ref.current!.open()}>click it</button> </RotateCaptcha> );}

基本属性介绍:

同时该组件接受5个方法,只有 onClose 和 result 是同步函数,其余全部为异步函数:

更详细的用法大家可以在github上学习参考:

https://github.com/cgfeel/react-rotate-captcha

demo 目前提供了 webpack 和 vite 版本的, 可以在: https://codesandbox.io/p/devbox/react-rotate-captcha-ts-react-vite-t23lcq 体验.

如果大家觉得不错, 欢迎点赞反馈, 不辜负每一位开源贡献者的努力, 让技术更美好~

0 阅读:0

科技趣谈有前端

简介:感谢大家的关注