Expand description
§reCAPTCHA v3 for Rocket Framework
This crate can help you use reCAPTCHA v3 (v2 is backward compatible) in your Rocket web application.
§Configuration
Put your reCAPTCHA keys in Rocket.toml. The html_key is optional, and is only needed to render the front-end script.
[default.recaptcha.v3]
html_key = "6Lf6dLIUAAAAAAxghN7nH6m_yuLfHwdD3N7FpanR"
secret_key = "6Lf6dLIUAAAAAHdJ4e0nsv-8OpFH-7Oad1XQ95rq"§Usage
Attach ReCaptcha::fairing to Rocket, and then every route can take a &State<ReCaptcha> to verify tokens with.
#[macro_use]
extern crate rocket;
use rocket::{State, form::Form};
use rocket_recaptcha_v3::{ReCaptcha, ReCaptchaToken};
#[derive(FromForm)]
struct LoginModel {
recaptcha_token: ReCaptchaToken,
}
#[get("/login")]
fn login_get(recaptcha: &State<ReCaptcha>) -> String {
// Render the front-end script with this key.
recaptcha.html_key().unwrap().as_str().to_string()
}
#[post("/login", data = "<model>")]
async fn login_post(recaptcha: &State<ReCaptcha>, model: Form<LoginModel>) -> &'static str {
match recaptcha.verify(&model.recaptcha_token, None).await {
Ok(verification) => {
if verification.score > 0.7 {
"Hello, human!"
} else {
"You are probably not a human."
}
},
Err(_) => "Please try again.",
}
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
rocket::build()
.attach(ReCaptcha::fairing())
.mount("/", routes![login_get, login_post])
.launch()
.await?;
Ok(())
}§reCAPTCHA v2
reCAPTCHA v2 works the same way. Put the keys under [default.recaptcha.v2], attach ReCaptcha::fairing_v2, and take a &State<ReCaptcha<V2>> in your routes. A solved v2 challenge carries no score, so ReCaptchaVerification::score is always 1.0 for it.
Both fairings can be attached to the same Rocket instance, because ReCaptcha<V3> and ReCaptcha<V2> are separate types.
§The client’s IP address
ReCaptcha::verify can report the client’s IP address to Google along with the token. Pass None to leave it out, or a ClientIp from the re-exported rocket_client_addr crate, which needs its ClientIpConfig in Rocket’s managed state.
#[macro_use]
extern crate rocket;
use rocket::{State, form::Form};
use rocket_recaptcha_v3::{
ClientIp, ReCaptcha, ReCaptchaToken,
rocket_client_addr::{ClientIpConfig, IpCidr},
};
#[derive(FromForm)]
struct LoginModel {
recaptcha_token: ReCaptchaToken,
}
#[post("/login", data = "<model>")]
async fn login_post(
recaptcha: &State<ReCaptcha>,
client_ip: &ClientIp,
model: Form<LoginModel>,
) -> &'static str {
match recaptcha.verify(&model.recaptcha_token, Some(client_ip)).await {
Ok(verification) if verification.score > 0.7 => "Hello, human!",
Ok(_) => "You are probably not a human.",
Err(_) => "Please try again.",
}
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
let client_ip_config = ClientIpConfig::builder()
.trusted_proxies()
.proxy("10.0.0.0/24".parse::<IpCidr>().unwrap())
.build()
.unwrap();
rocket::build()
.attach(ReCaptcha::fairing())
.manage(client_ip_config)
.mount("/", routes![login_post])
.launch()
.await?;
Ok(())
}Re-exports§
pub use chrono;pub use rocket_client_addr;pub use validators;
Structs§
- Client
Ip - The resolved client IP, and where it came from.
- ReCaptcha
- A pair of reCAPTCHA keys which can verify reCAPTCHA tokens.
- ReCaptcha
Fairing - A Rocket fairing which reads reCAPTCHA keys from the Rocket configuration and then manages a
ReCaptchainstance. - ReCaptcha
Key - A reCAPTCHA key, which is 40 characters of
0-9,a-z,A-Z,-and_. - ReCaptcha
Token - A reCAPTCHA token, which a client obtains from the reCAPTCHA front-end script and then sends to the server.
- ReCaptcha
Verification - A reCAPTCHA token which the
siteverifyAPI has accepted. - Regex
Error - Error from the
regexvalidator. - V2
- reCAPTCHA v2, which challenges the user and reports no score.
- V3
- reCAPTCHA v3, which scores a request instead of challenging the user.
Enums§
- ReCaptcha
Error - Errors of the
ReCaptchastruct. - ReCaptcha
Error Code - An error code reported by the
siteverifyAPI.
Constants§
- API_URL
- The endpoint of the
siteverifyAPI, which is what aReCaptchainstance uses by default. - API_
URL_ RECAPTCHA_ NET - An alternative endpoint of the
siteverifyAPI, for regions wheregoogle.comcannot be reached.
Traits§
- ReCaptcha
Variant - A version of reCAPTCHA. This trait is sealed, and
V3andV2are its only implementations.