easy-captcha✌️
Rust图形验证码,由Java同名开源库whvcse/EasyCaptcha移植而来👏,100%纯Rust实现,支持gif、算术等类型。
目前已适配框架:
更多框架欢迎您提交PR,参与适配🙏
效果展示
普通验证码
动态验证码
算术验证码
安装和使用
cargo add easy-captcha
若您正在使用的框架已适配,您可直接通过CaptchaUtil类(并导入相应框架的trait)来使用验证码:
use easy_captcha::extension::axum_tower_sessions::{
CaptchaAxumTowerSessionExt, CaptchaAxumTowerSessionStaticExt,
};
async fn get_captcha(session: Session) -> Result<Response, StatusCode> {
let mut captcha: CaptchaUtil<GifCaptcha> = CaptchaUtil::new();
match captcha.out(&session).await {
Ok(response) => Ok(response),
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
async fn verify_captcha(
session: Session,
Query(query): Query<HashMap<String, String>>,
) -> Response {
if let Some(code) = query.get("code") {
if CaptchaUtil::ver(code, &session).await {
CaptchaUtil::clear(&session).await; "Your code is valid, thank you.".into_response()
} else {
"Your code is not valid, I'm sorry.".into_response()
}
} else {
"You didn't provide the code.".into_response()
}
}
您也可以自定义验证码的各项属性:
async fn get_captcha(session: Session) -> Result<Response, StatusCode> {
let mut captcha: CaptchaUtil<GifCaptcha> = CaptchaUtil::with_size_and_len(127, 48, 4);
match captcha.out(&session).await {
Ok(response) => Ok(response),
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
项目当前提供了三种验证码实现:SpecCaptcha(静态PNG)、GifCaptcha(动态GIF)、ArithmeticCaptcha(算术PNG),您可按需使用。
项目内置字体:
| 字体 |
效果 |
| CaptchaFont::Font1 |
 |
| CaptchaFont::Font2 |
 |
| CaptchaFont::Font3 |
 |
| CaptchaFont::Font4 |
 |
| CaptchaFont::Font5 |
 |
| CaptchaFont::Font6 |
 |
| CaptchaFont::Font7 |
 |
| CaptchaFont::Font8 |
 |
| CaptchaFont::Font9 |
 |
| CaptchaFont::Font10 |
 |
未来工作计划
- 改进API设计,补充一些setter
- 移植原库的中文验证码功能
- 适配更多框架
- 编写单元测试和集成测试