#de #lib #la #et #jwt #service

easy-auth

简化密码生成和jwt编码解码的库

1 个不稳定版本

0.3.0 2023年4月16日

#587认证

MIT/Apache

9KB
124

easy auth

描述

这个库提供了两个非常容易使用的服务

  • 密码服务
  • 令牌服务

密码服务

pub trait PasswordService: Send + Sync {
    fn create_hash_password(&self, password: String) -> String;
    fn verifie(&self, password: String, hash: String) -> bool;
}

您可以使用结构体 PasswordServiceImplPasswordService 特征轻松生成和验证密码

令牌服务

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>;
}

您可以使用结构体 JwtTokenServiceTokenService 实现轻松编码和解码数据

示例

密码服务

#[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)
}

令牌服务

首先创建我们的结构体声明(exp 是一个必需字段),添加任何数据。

#[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()
    }
}
  • 编码示例
#[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())
}


  • 解码示例
#[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)
}

依赖项

~7–9.5MB
~271K SLoC