Webdev Tory
Webdev Tory

Reputation: 515

Decode JWT in Clojure/Java

I have a JWT string. I can paste it in to any of the top google results for "decode JWT" and it correctly decodes, and this without needing any secret or encryption statement from me. But all of the examples I see, e.g. Buddy or jwtt, require me to provide whatever secret they were encrypted with. How can I simply decode the raw string, as apparently easily as every website out there?

Upvotes: 2

Views: 1850

Answers (3)

number23_cn
number23_cn

Reputation: 4619

on https://jwt.io/ clojure JWT library: [funcool/buddy], doc:http://funcool.github.io/buddy-sign/latest/`

user=> (require '[buddy.sign.jwt :as jwt])
user=> (jwt/sign {:userid 1} "secret")
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjF9.5sxiy9q0YcpnXl2jBl-s4--C9iq5-4qC6CrW30NfRS4"
user=> (jwt/unsign "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjF9.5sxiy9q0YcpnXl2jBl-s4--C9iq5-4qC6CrW30NfRS4" "secret")
{:userid 1}
user=> 

Upvotes: 3

Webdev Tory
Webdev Tory

Reputation: 515

Answers below are informative and good; here is the Clojure version that worked for me:

(ns decode-jwt
  (:require [cheshire.core :as json])
  (:import [org.apache.commons.codec.binary Base64]))

(-> returned-jwt ;; returned-jwt is your full jwt string
    (clojure.string/split #"\.") ;; split into the 3 parts of a jwt, header, body, signature
    second ;; get the body
    Base64/decodeBase64 ;; read it into a byte array
    String. ;; byte array to string
    json/decode ;; make it into a sensible clojure map
    )

Upvotes: 3

xiaofeng.li
xiaofeng.li

Reputation: 8587

It's very simple to decode a JWT, but you should never trust the claims until you verified the signature. That's why any decent JWT library would require you to provide a secret, or the public key if it's signed using RSA.

Anyway, the format of a JWT is pretty simple -- three parts separated by .:

<header> . <payload> . <signature>

Each part is base64 encoded. So if you just want to see the claims, you can do something like this:

String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";
String [] jwtParts = jwt.split("\\.");
if (jwtParts.length == 3) {
    String payload = new String(Base64.getDecoder().decode(jwtParts[1]));
    System.out.println(payload);
    // Now you can use some JSON library to decode payload.
}

Upvotes: 3

Related Questions