Android Accessing JWT Payload – Decode JWT

You are currently viewing Android Accessing JWT Payload – Decode JWT

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. When I find it, I will post the link.

I have altered the function to suit my needs.

Code

JWTUtils

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
                
            }

Leave a Reply