Android parse token using JWT with Kotlin

I have a jwt token like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

How can I decode this so that I can get the payload like this:

Header:
{
  "alg": "HS256",
  "typ": "JWT"
}
Body:
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

In Android Kotlin, you can use below code to decode the JWT token.

Method #1

fun extractJwt(jwt: String): String {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return "Requires SDK 26"
    val parts = jwt.split(".")
    return try {
        val charset = charset("UTF-8")
        val header = String(Base64.getUrlDecoder().decode(parts[0].toByteArray(charset)), charset)
        val payload = String(Base64.getUrlDecoder().decode(parts[1].toByteArray(charset)), charset)
        "$header\n$payload"
    } catch (e: Exception) {
        "Error parsing JWT: $e"
    }
}

Method #2

import android.util.Base64
import org.json.JSONException

// Json data class
data class Data(
    val name: String?,
    val nonce: String?,
    // Other access_token fields
)

fun parseAccessToken(token: String): Data? {
    return try {
        val part = token.split(".")[1]
        val s = decodeJwt(part)
        // obj is an object of Gson or Moshi library
        obj.fromJson(s)
    } catch (e: Exception) {
        null
    }
}

@Throws(JSONException::class)
private fun decodeJwt(text: String): String {
    val s = Base64.decode(text, Base64.URL_SAFE)
    return String(s)
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

購物車