为什么我的 Kotlin 代码中的访问令牌不起作用?

Why is the access token from my Kotlin code not working?

我目前正在处理 Keycloak 身份验证。我从 java 代码中获得的令牌被我的服务器视为无效,但是如果我使用邮递员(几乎)完全相同的 URL 和相同的 urlencoded 值访问令牌,我从邮递员进入我的代码的 $token 区域,已正确验证。

我无法理解为什么会发生这种情况,除非它与 android localhost URL ("10.0.2.2") 弄乱了令牌有关。

这是我获取访问令牌的代码

  suspend fun login(username:String, password:String):String {

    val httpEndpoint = "http://10.0.2.2:8180/auth/realms/MYREALM/protocol/openid-connect/token"
    val myURL = URL(httpEndpoint)
    val myConnection2 = myURL.openConnection() as HttpURLConnection

    myConnection2.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
    myConnection2.requestMethod = "POST"
    myConnection2.doOutput = true

    val urlParamaters = "client_id=MYCLIENT&username=MYUSER&password=MYPASSWORD&grant_type=password"

    val os: OutputStream = myConnection2.getOutputStream()
    val osw = OutputStreamWriter(os, "UTF-8")


    osw.write(urlParamaters)
    osw.flush()
    osw.close()

    println(myConnection2.responseCode)

    val inputAsString = myConnection2.inputStream.bufferedReader().use { it.readText() }
    val jsonObj = JSONObject(inputAsString)
    val accessToken = jsonObj.getString("access_token")

    println(inputAsString)
    println(accessToken)

    return accessToken
}

这是我使用访问令牌的代码。

suspend fun catPost(token:String) {

    val httpEndpoint = URL("http://10.0.2.2:8080/users/cat")

    val myConnection2 = httpEndpoint.openConnection() as HttpURLConnection

    myConnection2.setRequestProperty("Authorization", "Bearer $token")

    myConnection2.requestMethod = "GET"

    println(myConnection2.responseCode)
    println(myConnection2.responseMessage)
    val inputAsString = myConnection2.inputStream.bufferedReader().use { it.readText() }

}

以及获取token的邮递员URL:

  http://localhost:8180/auth/realms/MYREALM/protocol/openid-connect/token

我刚刚解决了同样的问题。

请调试您在应用程序上获得的令牌。 尝试在此处对令牌进行编码,https://jwt.io/.

您可能会看到解码的令牌不完整(已损坏)。 有了这个迹象,我假设你忘了把

returnSecureToken = true 在请求正文上。

希望您在您出色的应用程序上做得很好!