11个版本
0.3.1 | 2023年5月9日 |
---|---|
0.3.0 | 2021年5月25日 |
0.2.4 | 2021年1月23日 |
0.2.3 | 2019年12月6日 |
0.1.2 | 2019年2月27日 |
#88 in 身份验证
15,622 每月下载
用于 18 个Crate(9直接)
58KB
1.5K SLoC
Rust实现Digest Auth哈希算法,如IETF RFC 2069、2617和7616所定义。
此Crate提供了身份验证头解析和生成代码。
请参阅文档和测试用例以获取示例。
lib.rs
:
此Crate实现了IETF RFC 2069、2617和7616中规定的Digest Auth头。它可以与reqwest等库一起使用,以访问例如使用此认证方案的IP相机。
该库是为http客户端编写的,但由于算法是对称的,因此也可以由服务器端使用。服务器端nonce管理(生成、定时过期)和授权检查留给用户实现。
可以使用 AuthorizationHeader::digest()
方法在服务器端复制密码/正文哈希;然后只需检查计算出的摘要是否与用户发送的摘要匹配即可。
示例
基本用法
use digest_auth::AuthContext;
// Value from the WWW-Authenticate HTTP header (usually in a HTTP 401 response)
let www_authenticate = r#"Digest realm="[email protected]", qop="auth, auth-int", algorithm=MD5, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#;
// Prepare an authorization context. Note that this is a GET request. There are different
// constructors available for POST or other request types. You can re-use it, but
// it's cheap to create a fresh one each time, as the struct uses references only.
let mut context = AuthContext::new("Mufasa", "Circle of Life", "/dir/index.html");
// For this test, we inject a custom cnonce. It's generated for you otherwise
// - you don't need `mut` in that case and needn't worry about this at all.
context.set_custom_cnonce("f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ");
// Parse the prompt header. You can inspect the parsed object, its fields are public.
let mut prompt = digest_auth::parse(www_authenticate).unwrap();
// Compute a value for the Authorization header that we'll send back to the server
let answer = prompt.respond(&context).unwrap().to_string();
assert_eq!(answer, r#"Digest username="Mufasa", realm="[email protected]", nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", uri="/dir/index.html", qop=auth, nc=00000001, cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ", response="8ca523f5e9506fed4657c9700eebdbec", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS", algorithm=MD5"#);
// The `prompt` variable is mutable, because the 'nc' counter (nonce reuse count)
// is inside the struct and updated automatically.
// You can re-use it for subsequent requests, assuming the server allows nonce re-use.
// Some poorly implemented servers will reject it and give you 401 again, in which case
// you should parse the new "WWW-Authenticate" header and use that instead.
let answer2 = prompt.respond(&context).unwrap().to_string();
// notice how the 'response' field changed - the 'nc' counter is included in the hash
assert_eq!(answer2, r#"Digest username="Mufasa", realm="[email protected]", nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", uri="/dir/index.html", qop=auth, nc=00000002, cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ", response="4b5d595ecf2db9df612ea5b45cd97101", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS", algorithm=MD5"#);
依赖项
~0.6–1MB
~18K SLoC