mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-02-23 04:52:28 +00:00
support cookie auth without cookie jar in state
This commit is contained in:
parent
4fd5464e44
commit
fee9dc89b0
1 changed files with 24 additions and 3 deletions
27
src/auth.rs
27
src/auth.rs
|
@ -8,7 +8,7 @@ use gotham::{
|
||||||
anyhow,
|
anyhow,
|
||||||
handler::HandlerFuture,
|
handler::HandlerFuture,
|
||||||
hyper::header::{HeaderMap, AUTHORIZATION},
|
hyper::header::{HeaderMap, AUTHORIZATION},
|
||||||
middleware::{Middleware, NewMiddleware},
|
middleware::{cookie::CookieParser, Middleware, NewMiddleware},
|
||||||
state::{FromState, State}
|
state::{FromState, State}
|
||||||
};
|
};
|
||||||
use jsonwebtoken::{errors::ErrorKind, DecodingKey};
|
use jsonwebtoken::{errors::ErrorKind, DecodingKey};
|
||||||
|
@ -209,8 +209,12 @@ where
|
||||||
// extract the provided token, if any
|
// extract the provided token, if any
|
||||||
let token = match &self.source {
|
let token = match &self.source {
|
||||||
AuthSource::Cookie(name) => CookieJar::try_borrow_from(&state)
|
AuthSource::Cookie(name) => CookieJar::try_borrow_from(&state)
|
||||||
.and_then(|jar| jar.get(&name))
|
.map(|jar| jar.get(&name).map(|cookie| cookie.value().to_owned()))
|
||||||
.map(|cookie| cookie.value().to_owned()),
|
.unwrap_or_else(|| {
|
||||||
|
CookieParser::from_state(&state)
|
||||||
|
.get(&name)
|
||||||
|
.map(|cookie| cookie.value().to_owned())
|
||||||
|
}),
|
||||||
AuthSource::Header(name) => HeaderMap::try_borrow_from(&state)
|
AuthSource::Header(name) => HeaderMap::try_borrow_from(&state)
|
||||||
.and_then(|map| map.get(name))
|
.and_then(|map| map.get(name))
|
||||||
.and_then(|header| header.to_str().ok())
|
.and_then(|header| header.to_str().ok())
|
||||||
|
@ -292,6 +296,7 @@ where
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
use cookie::Cookie;
|
use cookie::Cookie;
|
||||||
|
use gotham::hyper::header::COOKIE;
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
|
|
||||||
// 256-bit random string
|
// 256-bit random string
|
||||||
|
@ -458,4 +463,20 @@ mod test {
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_auth_middleware_cookie_no_jar() {
|
||||||
|
let cookie_name = "znoiprwmvfexju";
|
||||||
|
let middleware = new_middleware::<TestData>(AuthSource::Cookie(cookie_name.to_owned()));
|
||||||
|
State::with_new(|mut state| {
|
||||||
|
let mut headers = HeaderMap::new();
|
||||||
|
headers.insert(COOKIE, format!("{}={}", cookie_name, VALID_TOKEN).parse().unwrap());
|
||||||
|
state.put(headers);
|
||||||
|
let status = middleware.auth_status(&mut state);
|
||||||
|
match status {
|
||||||
|
AuthStatus::Authenticated(data) => assert_eq!(data, TestData::default()),
|
||||||
|
_ => panic!("Expected AuthStatus::Authenticated, got {:?}", status)
|
||||||
|
};
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue