Skip to content

Commit

Permalink
feat: add jwks endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
raimundo-henriques committed Nov 16, 2023
1 parent fac54bc commit 4b06896
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
9 changes: 8 additions & 1 deletion endpoint/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ impl<'r> FromRequest<'r> for UserToken {
req: &'r Request<'_>,
) -> request::Outcome<Self, status::Custom<UserTokenError>> {
if let Some(authen_header) = req.headers().get_one("Authorization") {
println!(
"request state: {:?}",
req.rocket().state::<KeyPair>().unwrap()
);
let authen_str = authen_header.to_string();
if authen_str.starts_with("Bearer") {
let token = authen_str[6..authen_str.len()].trim();
Expand Down Expand Up @@ -171,10 +175,13 @@ pub fn generate_keys() -> KeyPair {
}

fn decode_token(token: String, pub_key: String) -> Result<TokenData<UserToken>> {
let mut v = Validation::new(Algorithm::RS256);
v.validate_exp = false;

jsonwebtoken::decode::<UserToken>(
&token,
&DecodingKey::from_rsa_pem(pub_key.as_bytes()).unwrap(),
&Validation::new(Algorithm::RS256),
&v,
)
}

Expand Down
40 changes: 38 additions & 2 deletions endpoint/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ use auth::{generate_keys, UserToken};
use chrono::{DateTime, Utc};
use either::Either;

use jsonwebtoken::jwk::{
AlgorithmParameters, CommonParameters, Jwk, JwkSet, KeyAlgorithm, PublicKeyUse,
RSAKeyParameters,
};
use lambda_web::{is_running_on_lambda, launch_rocket_on_lambda, LambdaError};
use okapi::openapi3::{Object, Parameter, ParameterValue};
use rocket::catch;
Expand All @@ -41,7 +45,9 @@ use rocket_okapi::{get_openapi_route, openapi, openapi_get_routes_spec};
use api_types::*;
use datamodel::{PfId, ProductFootprint};
use openid_conf::OpenIdConfiguration;
use rsa::{RsaPrivateKey, RsaPublicKey};
use rsa::pkcs8::{self, DecodePublicKey};
use rsa::traits::PublicKeyParts;
use rsa::RsaPublicKey;
use sample_data::PCF_DEMO_DATA;
use Either::Left;

Expand Down Expand Up @@ -71,13 +77,43 @@ fn openid_configuration() -> Json<OpenIdConfiguration> {
Json(openid_conf)
}

#[get("/2/jwks")]
fn jwks(state: &State<KeyPair>) -> Json<JwkSet> {
println!("{:?}", state.pub_key);
let pub_key: RsaPublicKey =
pkcs8::DecodePublicKey::from_public_key_pem(&state.pub_key).unwrap();
let jwks = JwkSet {
keys: vec![Jwk {
common: CommonParameters {
public_key_use: Some(PublicKeyUse::Signature),
key_operations: None,
key_algorithm: Some(KeyAlgorithm::RS256),
key_id: Some("Public key".to_string()),
x509_url: None,
x509_chain: None,
x509_sha1_fingerprint: None,
x509_sha256_fingerprint: None,
},
algorithm: AlgorithmParameters::RSA(RSAKeyParameters {
key_type: jsonwebtoken::jwk::RSAKeyType::RSA,
n: pub_key.n().to_string(),
e: pub_key.e().to_string(),
}),
}],
};

Json(jwks)
}

/// endpoint to create an oauth2 client credentials grant (RFC 6749 4.4)
#[post("/token", data = "<body>")]
fn oauth2_create_token(
req: auth::OAuth2ClientCredentials,
body: Form<auth::OAuth2ClientCredentialsBody<'_>>,
state: &State<KeyPair>,
) -> Either<Json<auth::OAuth2TokenReply>, error::OAuth2ErrorMessage> {
println!("{state:?}");

if req.id == AUTH_USERNAME && req.secret == AUTH_PASSWORD {
let access_token = auth::encode_token(
&auth::UserToken { username: req.id },
Expand Down Expand Up @@ -432,7 +468,7 @@ fn create_server() -> rocket::Rocket<rocket::Build> {
rocket::build()
.mount("/", openapi_routes)
.mount("/", routes![get_list, get_pcf_unauth, post_event_fallback])
.mount("/", routes![openid_configuration])
.mount("/", routes![openid_configuration, jwks])
.mount("/2/auth", routes![oauth2_create_token])
.mount(
"/swagger-ui/",
Expand Down

0 comments on commit 4b06896

Please sign in to comment.