Acutally playing with rust and jwt, I am developing a dummy app that basically does two things: return a jwt token when user does login (it relies on github as idp),
...
let claim = Claims {
user_email: String::from(user_email.as_str()),
auth_provider: String::from("github"),
token: cookie_value.clone() //it is a String too
};
let token = sign_with_key(private_key, claim).unwrap();
return (
StatusCode::OK,
[(header::SET_COOKIE, token)],
Json(json!({
"user": user_email
}))
);
...
fn sign_with_key(private_key: String, user_claims: Claims) -> Result<String, String> {
println!("private_key: {}", private_key);
let encoding_key = EncodingKey::from_rsa_pem(private_key.as_bytes()).unwrap();
let token = encode(&Header::new(Algorithm::RS256), &user_claims,&encoding_key).unwrap();
return Ok(token);
}
and verify the token stored in the cookie,
pub async fn verify(Extension(public_key): Extension<String>, headers: HeaderMap) -> impl IntoResponse {
let cookie = headers.get("cookie");
let decoding_key = DecodingKey::from_rsa_pem(public_key.as_bytes()).unwrap();
println!("cookie {:?}, {}", cookie, &cookie.unwrap().to_str().unwrap());
match decode::<Claims>(&cookie.unwrap().to_str().unwrap(), &decoding_key, &Validation::new(Algorithm::RS256)) {
Ok(token_data) => {
println!("token inner user_email {:?}", token_data.claims.user_email);
return StatusCode::OK;
},
Err(e) => {
println!("ERROR: {:?}", e);
return StatusCode::UNAUTHORIZED;
}
}
}
private_key
and public_key
are respectively obtained by the following commands:
openssl genrsa -out keymaster.private.pem 2048
openssl rsa -in keymaster.private.pem -pubout > keymaster.public.pem
I was expecting that the token I got by running the first code to be positively verified by the verify
function but I am getting an InvalidSignature
error. What am I doing wrong?