1 unstable release
0.3.0 | Apr 16, 2023 |
---|
#726 in Authentication
9KB
124 lines
easy auth
description
Cette lib met à disposition deux services vraiment facile à utiliser :
- PasswordService
- TokenService
PasswordService
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
TokenService
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
Exemples
PasswordService
#[test]
fn password_should_be_verfied_when_compared_with_hashed_and_salt() {
// given
let salt = "salt_test";
let password_service = PasswordServiceImpl::new(salt.to_string());
let password = "mon_mot_de_passe";
let password_hashed_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)
}
TokenService
Commençons par creer notre struct claims (exp est un champ obligatoire), mettez n'importe quelle données avec.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
struct Claims {
sub: String,
exp: usize,
pseudo: String
}
fn claim_test_with_expired() -> Claims {
claim_from_exp(1358781921)
}
fn claim_test_valid() -> Claims {
claim_from_exp(
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as usize + 3600
)
}
fn claim_from_exp(exp: usize) -> Claims {
Claims {
sub: "test_sub".to_string(),
exp,
pseudo: "pseudo_test".to_string()
}
}
- encode exemple :
#[test]
fn encode_should_generate_jwt_token() {
// given
let secret_key = "my_secret_key";
let jwt_token_service = JwtTokenService::new(secret_key.to_string());
let claims = claim_test_valid();
let expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0X3N1YiIsImV4cCI6MTM1ODc4MTkyMSwicHNldWRvIjoicHNldWRvX3Rlc3QifQ.jV6TRv2GgyeniAwDVboXzbf2ftLczlHr5U6Uux6IOHk";
// when
let result = jwt_token_service.encode(claims);
// then
assert_eq!(result, expected.to_string())
}
- decode exemple :
#[test]
fn decode_should_give_claims_from_jwt() {
// given
let secret_key = "my_secret_key";
let jwt_token_service = JwtTokenService::new(secret_key.to_string());
let claims_expected = claim_test_valid(); // current timestamp + 3600
let jwt_for_decoding = jwt_token_service.encode(claims_expected.clone());
// when
let result = jwt_token_service
.decode::<Claims>(jwt_for_decoding.as_str())
.unwrap();
// then
assert_eq!(result, claims_expected)
}
Dependencies
~7–10MB
~279K SLoC