解码令牌JWT android kotlin?



我有一个这样的标记:

hereeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcGVyYWRvciI6eyJpZCI6NzAsIm5vbWUiOiJERUlWSVRJIiwidXN1YXJpbyI6IkRFSVZJVEkifSwiaWF0IjoxNjI5ODEyNDA1fQ.JqzQnFSbG6gFsnlJu3-bezxZ_N5e5FEzc9QvpRGu0u4

隐藏它:

alg: "HS256",
typ: "JWT"
}.
operador: {
id: 20,
nome: "JOAO",
usuario: "JOAO"
},
iat: 1629812405
}

问题是我如何在android kotlin上只有用户id在某些任务中使用?

我只是修复了这个问题:

private fun decodeToken(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"
"$payload"
} catch (e: Exception) {
"Error parsing JWT: $e"
}
}

:

val mDecode = decodeToken(mToken)
val test = JSONObject(mDecode).getString("operador")
val mDecodeTokenOk = JSONObject(test).getString("id")
/** SALVANDO ID_OPERADOR */
mSharedPreferences.saveString(WmsConstantes.ID_OPERADOR,mDecodeTokenOk)
Log.e("------------------>", mDecodeTokenOk.toString());

你可以用这个,

https://github.com/auth0/JWTDecode.Android

假设iat值是用户id,

var jwt: JWT = JWT(YOUR_TOKEN_STRING)
var claim: Claim = jwt.getClaim("iat")
//or as a string
var claim: String = jwt.getClaim("iat").asString()

您不需要安装任何库。你可以试试这样做。

  • 反映JWT有效载荷的类别
data class JwtPayload(
@SerializedName("iat")
val iat: Int,
@SerializedName("operador")
val operador: Operador
)
data class Operador(
@SerializedName("id")
val id: Int,
@SerializedName("nome")
val nome: String,
@SerializedName("usuario")
val usuario: String
)
  • 您可以使用该类作为令牌的包装器
class Jwt(private val token: String) {
private val userData: JsonObject by lazy {
val userData = String(Base64.decode(token.split(".")[1], Base64.DEFAULT), StandardCharsets.UTF_8)
JsonParser.parseString(userData).asJsonObject
}
fun getUserData(): JwtPayload{
gson.toJson(userData, Jwt::class.java)
return gson.fromJson(userData, JwtPayload::class.java)
}
fun isExpired(): Boolean {
return userData.asJsonObject.get("exp").asLong < (System.currentTimeMillis() / 1000)
}
companion object {
@JvmStatic
private val gson = Gson()
}
}
使用
val token = Jwt("YOUR_TOKEN")
val operatorID = token.operator.id

您可以将此解析方法用于任何类

@JvmStatic
private val gsonRef = Gson()
@JvmStatic
private val parserRef = JsonParser()
fun Parse(token: String) : DecodedLoginToken {
val delimittedData = String(Base64.decode(token.split(".")[1], Base64.DEFAULT), StandardCharsets.UTF_8)
val result = gsonRef.fromJson(delimittedData, DecodedLoginToken::class.java)
return result
}

相关内容

  • 没有找到相关文章