medallion/examples/rs256.rs

49 lines
1.6 KiB
Rust
Raw Normal View History

2017-02-14 15:51:39 +00:00
extern crate medallion;
extern crate openssl;
2017-02-13 23:40:07 +00:00
use std::default::Default;
use openssl::rsa;
use medallion::{Algorithm, Header, DefaultPayload, DefaultToken};
2017-02-13 23:40:07 +00:00
fn new_token(private_key: &[u8], user_id: &str, password: &str) -> Option<String> {
// dummy auth, in a real application using something like openidconnect, this would be some
// specific authentication scheme that takes place first then the JWT is generated as part of
// sucess and signed with the provider's private key so other services can validate trust for
// the claims in the token
2017-02-13 23:40:07 +00:00
if password != "password" {
return None;
2017-02-13 23:40:07 +00:00
}
// can satisfy Header's type parameter with an empty tuple
let header: Header<()> = Header { alg: Algorithm::RS256, ..Default::default() };
let payload: DefaultPayload = DefaultPayload {
2017-02-14 15:51:39 +00:00
iss: Some("example.com".into()),
2017-02-13 23:40:07 +00:00
sub: Some(user_id.into()),
..Default::default()
};
let token = DefaultToken::new(header, payload);
2017-02-13 23:40:07 +00:00
token.sign(private_key).ok()
2017-02-13 23:40:07 +00:00
}
fn login(public_key: &[u8], token: &str) -> Option<String> {
let token: DefaultToken<()> = DefaultToken::parse(token).unwrap();
2017-02-13 23:40:07 +00:00
if token.verify(public_key).unwrap() {
token.payload.sub
2017-02-13 23:40:07 +00:00
} else {
None
}
}
fn main() {
// alternatively can read .pem files from fs or fetch from a server or...
let keypair = rsa::Rsa::generate(2048).unwrap();
let token = new_token(&keypair.private_key_to_pem().unwrap(), "Random User", "password").unwrap();
2017-02-13 23:40:07 +00:00
let logged_in_user = login(&keypair.public_key_to_pem().unwrap(), &*token).unwrap();
2017-02-13 23:40:07 +00:00
2017-02-14 15:51:39 +00:00
assert_eq!(logged_in_user, "Random User");
2017-02-13 23:40:07 +00:00
}