如何在Android上正确请求OAuth令牌?

时间:2019-01-21 15:19:24

标签: android kotlin oauth httpurlconnection

我有一个需要连接到网络服务的android应用。我目前正在尝试实施登录。我有client_id,client_secret,grant_type,密码,范围和用户名,但我需要获取access_token。

我已经尝试实现this answerthe solution in this question

在下面的代码中,我还尝试将requestMethod切换为“ POST”,并且注释的部分也是我尝试过的替代方法。

import android.app.Activity
import android.util.Base64
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL

object ServerConnection {

    private const val TAG = "ServerConnection"

    var token: String? = null
            private set

    fun login(username: String, password: String, baseUrl: String, clientId: String, clientSecret: String, grantType: String, scope: String): Boolean {
        //val payload = """{username: "$username", password: "$password", grant_type: "$grantType", client_id: "$clientId", scope: "$scope", client_secret: "$clientSecret"}"""
        //val payload = """grant_type=$grantType&username=$username&password=$password&scope=$scope"""
        val payload = """client_id=$clientId&client_secret=$clientSecret&grant_type=$grantType&username=$username&password=$password&scope=$scope"""
        //val authorization = "Basic " + Base64.encodeToString(("$clientId:$clientSecret").toByteArray(), Base64.NO_WRAP)

        return login("$baseUrl/oauth/token", payload/*, authorization*/)
    }

    private fun login(url: String, payload: String/*, authorization: String*/): Boolean {
        val urlObject = URL(url)
        val connection = urlObject.openConnection() as HttpURLConnection

        connection.doOutput = true
        connection.requestMethod = "GET"
        connection.setRequestProperty("Accept", "application/json")
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
        //connection.setRequestProperty("Authorization", authorization)
        //connection.setRequestProperty("Content-Type", "application/json;odata=verbose")
        //connection.setRequestProperty("Authorization", "Basic Base64_encoded_clientId:clientSecret")
        //connection.setRequestProperty("Accept", "application/x-www-form-urlencoded")

        val outputStream = connection.outputStream
        outputStream.write(payload.toByteArray())
        outputStream.flush()
        outputStream.close()

        val responseCode = connection.responseCode
        Log.i(TAG, "GET Response Code :: $responseCode")

        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            val bufferedReader = BufferedReader(InputStreamReader(connection.inputStream))
            var inputLine: String
            val response = StringBuffer()

            do {

                inputLine = bufferedReader.readLine()

                if (inputLine == null) break

                response.append(inputLine)

            } while (true)
            bufferedReader.close()

            // log result
            Log.d(TAG, response.toString())
            token = response.toString()
        } else {
            Log.i(TAG, "GET request not worked")
            return false
        }

        return true
    }

}

我不确定我从StringBuffer response获得的字符串是否实际上是令牌,但是我希望至少能到达它。

实际上,它甚至无法到达那里,因为responseCode始终是400

0 个答案:

没有答案