Skip to content

Commit 7ce4d5c

Browse files
authored
Trim potential whitespace around jwt before decoding (#120)
Given that JWTs are base64 encoded and can thus not have leading or trailing whitespace, it is safe to trim the string before decoding (e.g. the decoder on jwt.io appears to do the same). This is mostly a convenience feature for people using jwt-cli like this: # pbpaste prints the text from the clipboard on macOS pbpaste | jwt decode - When copying from UIs such the Fx developer tools it's not always trivial to copy the value without any whitespace, and this change avoids the extra step of having to remove that whitespace manually. Of course e.g. piping through `xargs` would also be an option, but is, in my opinion, very obscure especially when used in scripts.
1 parent 238818d commit 7ce4d5c

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/main.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,10 @@ fn decode_token(
454454

455455
buffer
456456
})
457-
.unwrap();
457+
.unwrap()
458+
.trim()
459+
.to_owned();
460+
458461
let secret_validator = create_validations(algorithm);
459462

460463
(

tests/jwt-cli.rs

+15
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,21 @@ mod tests {
466466
assert!(result.is_ok());
467467
}
468468

469+
#[test]
470+
fn decodes_a_token_with_leading_and_trailing_whitespace() {
471+
let matches = config_options()
472+
.get_matches_from_safe(vec![
473+
"jwt",
474+
"decode",
475+
" eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.SEQijh6tEuOOAAKpHPuKxgFqEvlTNP1jj4FUNoBwXaM ",
476+
])
477+
.unwrap();
478+
let decode_matches = matches.subcommand_matches("decode").unwrap();
479+
let (result, _, _) = decode_token(&decode_matches);
480+
481+
assert!(result.is_ok());
482+
}
483+
469484
#[test]
470485
fn encodes_and_decodes_an_rsa_token_using_key_from_file() {
471486
let body: String = "{\"field\":\"value\"}".to_string();

0 commit comments

Comments
 (0)