oxide-auth
A OAuth2 server library, for use in combination with iron or other frontends, featuring a set of configurable and pluggable backends.
About
oxide-auth
aims at providing a comprehensive and extensible interface to managing oauth2 tokens on a server. While the core package is agnostic of the used frontend, an optional iron adaptor is provided with the default configuration. Through an interface designed with traits, the frontend is as easily pluggable as the backend.
Example
extern crate oxide_auth;
extern crate iron;
extern crate router;
use oxide_auth::iron::prelude::*;
use iron::prelude::*;
use std::thread;
use iron::modifier::Modifier;
use router::Router;
pub fn main() {
let passphrase = "This is a super secret phrase";
let ohandler = IronGranter::new(
ClientMap::new(),
Storage::new(RandomGenerator::new(16)),
TokenSigner::new_from_passphrase(passphrase));
let client = Client::public("LocalClient", "http://localhost:8021/endpoint".parse().unwrap(), "default".parse().unwrap()); ohandler.registrar().unwrap().register_client(client);
let mut router = Router::new();
router.get("/authorize", ohandler.authorize(handle_get), "authorize");
router.post("/authorize", ohandler.authorize(IronOwnerAuthorizer(handle_post)),
"authorize");
router.post("/token", ohandler.token(), "token");
let mut protected = iron::Chain::new(|_: &mut Request| {
Ok(Response::with((iron::status::Ok, "Hello World!")))
});
protected.link_before(ohandler.guard(vec!["default".parse::<Scope>().unwrap()]));
protected.link_after(HelpfulAuthorizationError());
router.get("/", protected, "protected");
let server = thread::spawn(||
iron::Iron::new(router).http("localhost:8020").unwrap());
server.join().expect("Failed to run");
}
fn handle_get(_: &mut Request, auth: &PreGrant) -> Result<(Authentication, Response), OAuthError> {
let text = format!(
"<html>'{}' (at {}) is requesting permission for '{}'",
grant.client_id, grant.redirect_url, grant.scope, grant.client_id, grant.client_id);
let response = Response::with((
iron::status::Ok,
iron::modifiers::Header(iron::headers::ContentType::html()), text));
Ok((Authentication::InProgress, response))
}
fn handle_post(req: &mut Request) -> IronResult<Response> {
req.extensions.insert::<Authentication>(Authentication::Failed);
Ok(Response::with(iron::status::Ok))
}
struct HelpfulAuthorizationError();
impl iron::middleware::AfterMiddleware for HelpfulAuthorizationError {
fn catch(&self, _: &mut Request, err: iron::IronError) -> IronResult<Response> {
if !err.error.is::<OAuthError>() {
return Err(err);
}
let mut response = err.response;
let text =
"<html>
This page is only accessible with an oauth token, scope <em>default</em>.
</html>";
text.modify(&mut response);
iron::modifiers::Header(iron::headers::ContentType::html()).modify(&mut response);
Ok(response)
}
}