4个版本

0.2.1 2024年8月1日
0.2.0 2024年7月26日
0.1.1 2023年4月6日
0.1.0 2022年12月16日

#634 in 认证

Download history 824/week @ 2024-04-16 726/week @ 2024-04-23 802/week @ 2024-04-30 868/week @ 2024-05-07 679/week @ 2024-05-14 366/week @ 2024-05-21 507/week @ 2024-05-28 556/week @ 2024-06-04 421/week @ 2024-06-11 590/week @ 2024-06-18 578/week @ 2024-06-25 315/week @ 2024-07-02 599/week @ 2024-07-09 301/week @ 2024-07-16 406/week @ 2024-07-23 720/week @ 2024-07-30

2,070 每月下载量
用于26个crate(直接使用6个)

Apache-2.0Apache-2.0…

340KB
7.5K SLoC

遵循RFC7519的JSON Web Token (JWT)实现。

使用方法

解码与验证

use serde_json::json;
use ssi_jwk::JWK;
use ssi_jws::CompactJWSStr;
use ssi_jwt::ToDecodedJWT;

let jws = CompactJWSStr::new(b"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBTbWl0aCIsImlhdCI6MTcxNTM0Mjc5MCwiaXNzIjoiaHR0cDovL2V4YW1wbGUub3JnLyNpc3N1ZXIifQ.S51Gmlkwy4UxOhhc4nVl4_sHHVPSrNmjZDwJCDXDbKp2MT8-UyhZLw03gVKe-JRUzcsteWoeRCUoA5rwnuTSoA").unwrap();

let jwk: JWK = json!({
    "kty": "EC",
    "use": "sig",
    "crv": "P-256",
    "x": "dxdB360AJqJFYhdctoKZD_a_P6vLGAxtEVaCLnyraXQ",
    "y": "iH6o0l5AECsfRuEw2Eghbrp-6Fob3j98-1Cbe1YOmwM",
    "alg": "ES256"
}).try_into().unwrap();

assert!(jws.verify_jwt(&jwk).await.unwrap().is_ok());

内部使用ToDecodedJWT::verify_jwt通过ToDecodedJWT::to_decoded_jwt解码JWT,然后通过DecodedJWS::verify验证签名和注册声明。

签名

使用JWSPayload::sign方法将有效载荷签名成JWT。

use serde_json::json;
use ssi_jwk::JWK;
use ssi_jws::JWSPayload;
use ssi_jwt::{JWTClaims, Issuer, IssuedAt, ExpirationTime};

let mut claims: JWTClaims = Default::default();
claims.registered.set(Issuer("http://example.org/#issuer".parse().unwrap()));
claims.registered.set(IssuedAt("1715342790".parse().unwrap()));
claims.registered.set(ExpirationTime("1746881356".parse().unwrap()));
claims.private.set("name".to_owned(), "John Smith".into());

let jwk: JWK = json!({
    "kty": "EC",
    "d": "3KSLs0_obYeQXfEI9I3BBH5y7aOm028bEx3rW6i5UN4",
    "use": "sig",
    "crv": "P-256",
    "x": "dxdB360AJqJFYhdctoKZD_a_P6vLGAxtEVaCLnyraXQ",
    "y": "iH6o0l5AECsfRuEw2Eghbrp-6Fob3j98-1Cbe1YOmwM",
    "alg": "ES256"
}).try_into().unwrap();

let jwt = claims.sign(&jwk).await.unwrap();
assert_eq!(jwt, "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vZXhhbXBsZS5vcmcvI2lzc3VlciIsImV4cCI6MTc0Njg4MTM1NiwiaWF0IjoxNzE1MzQyNzkwLCJuYW1lIjoiSm9obiBTbWl0aCJ9.zBfMZzfQuuSfzcZmnz0MjXwT1sP26qwVq2GZX3qL0DR3wRMVG-wbCu9jPJ48l-F_q7W253_VqMWpoLluHo-gpg")

依赖项

~20–34MB
~497K SLoC