【发布时间】:2021-02-25 15:11:30
【问题描述】:
我目前正在搞乱 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的邮递员网址:
http://localhost:8180/auth/realms/MYREALM/protocol/openid-connect/token
【问题讨论】:
-
此代码不是 Java。是 Kotlin 吗?
-
请在您的问题上使用正确的标签
-
刚改了,是Kotlin
标签: android kotlin keycloak httpurlconnection access-token