Cette lib met à disposition deux services vraiment facile à utiliser :
rust
pub trait PasswordService: Send + Sync {
fn create_hash_password(&self, password: String) -> String;
fn verifie(&self, password: String, hash: String) -> bool;
}
Vous pouvez facilement générer et vérifier un mot de passe en utilisant
l'implémentation du trait PasswordService avec la struct PasswordServiceImpl
rust
pub trait TokenService {
fn encode<'a, CLAIMS: Debug + Serialize + Deserialize<'a>>(&self, claims: CLAIMS) -> String;
fn decode<CLAIMS: Debug + Serialize + DeserializeOwned>(&self, token: &str) -> Result<CLAIMS, DecodeError>;
}
Vous pouvez facilement encode et decoder des données en utilisant l'implementation du service TokenService avec la struct JwtTokenService
```rust
fn passwordshouldbeverfiedwhencomparedwithhashedandsalt() { // given let salt = "salttest"; let passwordservice = PasswordServiceImpl::new(salt.tostring()); let password = "monmotdepasse"; let passwordhashed_salt = "$2y$12$a0DqbD7yXVLyKB.uKB.uK.OacqAixOlKJF6yowQChMdIuJ9EHTc4K"; let expected = true;
// when
let result = password_service.verifie(password.to_string(), password_hashed_salt.to_string());
// then
assert_eq!(result, expected)
} ```
Commençons par creer notre struct claims (exp est un champ obligatoire), mettez n'importe quelle données avec.
```rust
struct Claims { sub: String, exp: usize, pseudo: String }
fn claimtestwithexpired() -> Claims { claimfrom_exp(1358781921) }
fn claimtestvalid() -> Claims { claimfromexp( SystemTime::now().durationsince(SystemTime::UNIXEPOCH).unwrap().as_secs() as usize + 3600 ) }
fn claimfromexp(exp: usize) -> Claims { Claims { sub: "testsub".tostring(), exp, pseudo: "pseudotest".tostring() } } ```
```rust
fn encodeshouldgeneratejwttoken() { // given let secretkey = "mysecretkey"; let jwttokenservice = JwtTokenService::new(secretkey.tostring()); let claims = claimtest_valid(); let expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0X3N1YiIsImV4cCI6MTM1ODc4MTkyMSwicHNldWRvIjoicHNldWRvX3Rlc3QifQ.jV6TRv2GgyeniAwDVboXzbf2ftLczlHr5U6Uux6IOHk";
// when
let result = jwt_token_service.encode(claims);
// then
assert_eq!(result, expected.to_string())
}
```
```rust
fn decodeshouldgiveclaimsfromjwt() { // given let secretkey = "mysecretkey"; let jwttokenservice = JwtTokenService::new(secretkey.tostring()); let claimsexpected = claimtestvalid(); // current timestamp + 3600 let jwtfordecoding = jwttokenservice.encode(claimsexpected.clone());
// when
let result = jwt_token_service
.decode::<Claims>(jwt_for_decoding.as_str())
.unwrap();
// then
assert_eq!(result, claims_expected)
} ```