Search code examples
androidkotlinkeycloakhttpurlconnectionaccess-token

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


I am currently messing around with Keycloak authentication. The token I am getting from my java code is being deemed invalid by my server, but if I use postman with (almost) the exact same URL and same urlencoded values the access token, which I copy from postman into the $token area of my code, is correctly authenticated.

I can't wrap my head around why this might be happening, unless it's something to do with the android localhost URL ("10.0.2.2") messing up the token.

Here is my code for obtaining the access token

  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
}

Here is my code using the access token.

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() }

}

And the postman URL for obtaining the token:

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

Solution

  • I just solved the same problem.

    Please debug the token you gained on the app. Try to encode the token here, https://jwt.io/.

    You may see that the decoded token is not complete (corrupted). With that indication, I assume that you forgot to put

    returnSecureToken = true on the request body.

    Hope you doing good on your amazing app!