如何获取Authorization Bearer header?

How to get the Authorization Bearer header?

我想获得用于 OAuth 目的的授权持有人 header,但阅读文档看起来有点混乱

use nickel::{Nickel, JsonBody, HttpRouter, Request, Response, MiddlewareResult, MediaType};

    // Get the full Authorization header from the incoming request headers
    let auth_header = match request.origin.headers.get::<Authorization<Bearer>>() {
        Some(header) => header,
        None => panic!("No authorization header found")
    };

这会产生错误:

src/main.rs:84:56: 84:86 error: the trait hyper::header::HeaderFormat is not implemented for the type hyper::header::common::authorization::Authorization<hyper::header::common::authorization::Bearer> [E0277]

看看实现,我认为是正确的:

https://github.com/hyperium/hyper/blob/master/src/header/common/authorization.rs

impl<S: Scheme + Any> HeaderFormat for Authorization<S> where <S as FromStr>::Err: 'static {
    fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(scheme) = <S as Scheme>::scheme() {
            try!(write!(f, "{} ", scheme))
        };
        self.0.fmt_scheme(f)
    }
}

https://github.com/auth0/rust-api-example/issues/1

查看 Authorization 的文档,我们可以看到它确实实现了 Header:

impl<S: Scheme + Any> Header for Authorization<S>
    where S::Err: 'static

所以你走对了路。我的猜测是您 运行 陷入了更阴险的境地:同一个 crate 的多个版本。

具体来说,我今天编译的nickel版本(0.7.3),依赖于hyper 0.6.16。但是,如果我将 hyper = "*" 添加到我的 Cargo.toml,那么我 也会 获得最新版本的 hyper - 0.7.0.

hyper 0.7 中的项目与 hyper 0.6 中的项目不兼容,这看起来可能不直观。这也不是关于 hyper 的具体内容;所有板条箱都是如此。

如果您更新依赖项以锁定到 nickel 想要的相同版本的 hyper,那么您就可以开始了。


Cargo.toml

# ...

[dependencies]
hyper = "0.6.16"
nickel = "*"

src/main.rs

extern crate nickel;
extern crate hyper;

use hyper::header::{Authorization, Bearer};
use nickel::{HttpRouter, Request};

fn foo(request: Request) {
    // Get the full Authorization header from the incoming request headers
    let auth_header = match request.origin.headers.get::<Authorization<Bearer>>() {
        Some(header) => header,
        None => panic!("No authorization header found")
    };
}

fn main() {}