Created
May 1, 2019 14:44
-
-
Save mykhailokrainik/ce6a233d7430043ea52414c5a25c7459 to your computer and use it in GitHub Desktop.
Rust Rocket Basic Authorization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate rocket; | |
use rocket::{Request, Outcome}; | |
pub struct BasicAuth { | |
pub username: Option<String>, | |
pub password: Option<String>, | |
} | |
impl<'a, 'r> FromRequest<'a, 'r> for BasicAuth { | |
type Error = &'static str; | |
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> { | |
let auth_pair: Vec<&str> = request.headers().get_one("Authorization").unwrap_or("") | |
.split_whitespace() | |
.collect(); | |
match (auth_pair.get(0), auth_pair.get(1)) { | |
(Some(&"Basic"), Some(&token)) => { | |
let bytes = base64::decode(&token).unwrap_or(vec![]); | |
let strigfy: Vec<String> = std::str::from_utf8(&bytes) | |
.unwrap_or("") | |
.split(":") | |
.map(ToOwned::to_owned) | |
.collect(); | |
Outcome::Success(BasicAuth { | |
username: strigfy.get(0).map(ToOwned::to_owned), | |
password: strigfy.get(1).map(ToOwned::to_owned) | |
}) | |
}, | |
_ => Outcome::Failure((Status::Unauthorized, "No basic authorization")) | |
} | |
} | |
} | |
/// Example | |
/// | |
/// #[get("/")] | |
/// fn dashboard(auth: BasicAuth) -> Result<&'static str, ()> { | |
/// Ok("ok") | |
/// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment