This post I will show you what I use to decode JWT to view the header and payload in Android.
I do not claim to be the owner/writer of this code snippet. The main functions were gathered from searching various posts when I started my JWT journey and I am unable to find where it was from. I have altered the function to suit my needs.
There is a quite a bit of information to learn from JWT management. Please do your research on this topic to ensure full proper implementation.
Below is a link I am posting on how a JWT is built and encoded. It would be worth looking at and utilizing the tool they posted.
There are 3 main parts to a JWT:
- The header which is fundamentally the type of JWT and how it was created
- The payload carries what information you want to send. IE user ID, JWT IAT ( issued at ), etc
- The signature is what is used on client and server side to ensure the JWT is authentic. It is created by encrypting the header and payload.
Code
JWTUtils is the primary tool used to decode JWT.
object JWTUtils {
@Throws(Exception::class)
fun decoded(JWTEncoded: String) : MutableList<Any> {
try {
val arr = mutableListOf<Any>()
val split =
JWTEncoded.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var s = getJson(split[0])
val header : JWTHeader = Gson().fromJson(s, JWTHeader::class.java)
arr.add(header)
s = getJson(split[1])
val body : JWTBody = Gson().fromJson(s, JWTBody::class.java)
arr.add(body)
//val header: JsonObject = JsonObject().getAsJsonObject(getJson(split[0]))
//val body: JsonObject = JsonObject().getAsJsonObject(getJson(split[1]))
//Log.d("JWT_DECODED", "Body: " + getJson(split[1]))
return arr
} catch (e: UnsupportedEncodingException) {
//Error
}
return mutableListOf()
}
private fun getJson(strEncoded: String): String {
val decodedBytes: ByteArray = Base64.decode(strEncoded, Base64.URL_SAFE)
return String(decodedBytes, charset("UTF-8"))
}
fun processJWT(acc_token : String) : MutableList<Any>{
Log.i("Access Token Received", acc_token)
val decoded = JWTUtils.decoded(acc_token)
return decoded
}
}
JWTHeader data type
data class JWTHeader (
@SerializedName("alg")
val alg : String,
@SerializedName("typ")
val typ : String
)
JWTBody ( the payload ) - this could vary
data class JWTBody (
@SerializedName("id")
val id : Int,
@SerializedName("username")
val username : String,
@SerializedName("job")
val job : String,
@SerializedName("iat")
val iat : String
)
To use it, do the following
val decoded = JWTUtils.decoded(acc_token)
if (decoded.isNotEmpty()) {
val header: JWTHeader = decoded[0] as JWTHeader
val body: JWTBody = decoded[1] as JWTBody
//process
}