使用服务账号获取访问令牌的方法

huangapple go评论70阅读模式
英文:

How to get access token Using Service Account

问题

我想使用服务账号获取访问令牌,但问题是在哪里放置json文件?如何链接它。在文档部分没有适当的指导。我需要一个asynctask吗?

以下是代码部分:

HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();

GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(HTTP_TRANSPORT)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId("")
    .setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher")
    .setServiceAccountPrivateKeyFromP12File(keyFile) // 在哪里放置json文件?
    .build();
AccessToken accessToken = credentials.refreshAccessToken();
英文:

I want to get access token using service account but the problem is where to put the json file ? How to link it . In doc section there is no proper guidelines . Do i need a asynctask ?

Here is the code :

    HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    JsonFactory JSON_FACTORY = new JacksonFactory();
    
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId("")
        .setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher")
        .setServiceAccountPrivateKeyFromP12File(keyFile) // where to put the json file?
        .build();
      AccessToken accessToken = credentials.refreshAccessToken();

答案1

得分: 2

以下是从服务帐户获取访问令牌的步骤。

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        authExplicit()
    }
    
    fun authExplicit() {
        CoroutineScope(Dispatchers.Default).launch {
            try {
                val credentials =
                    GoogleCredentials.fromStream(resources.assets.open("studentsamplechatbot-xvgloa.json"))
                        .createScoped(Collections.singletonList("https://www.googleapis.com/auth/dialogflow"))
                credentials.refreshIfExpired()
                val accessToken = credentials.accessToken
                Log.e("log_data", "Token : " + accessToken.tokenValue)
                if (accessToken.tokenValue.isNotEmpty()) {
                    Log.e(
                        "log_data",
                        "Got it --> authenticationType : " + credentials.authenticationType
                    )
                    AuthToken = "Bearer " + accessToken.tokenValue
                } else {
                    Log.e("log_data", "No token")
                    AuthToken = ""
                }
                CoroutineScope(Dispatchers.Main).launch {
                    initViews()
                }
            } catch (e: Exception) {
                Log.e("log_data", e.toString())
            }
        }
    }
}

你可以从Google Cloud Platform下载它:

  1. Google Cloud Platform -> 选择你的项目 -> IAM 和管理 -> 服务帐户 -> 创建服务帐户

  2. 创建服务帐户将打开一个页面,上面有一些细节,添加详细信息并创建它。

  3. 创建服务帐户后,你可以在列表中找到一个已创建的服务帐户。

  4. 从右侧,有一个包含三个点的操作列。从中选择一个选项创建密钥。当你点击它时,将打开一个对话框,上面有两个选项JSONP12。当你选择JSON并点击创建时,它将下载你的服务帐户的JSON文件。

  5. 你可以将此JSON文件用于你的Android项目,并将其放入assets文件夹中。
    你的项目 -> app -> src -> main -> assets

  6. 你可以使用上述函数来获取访问令牌。

英文:

Steps for the getting access token from Service account.

  class MainActivity : AppCompatActivity() {
          override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_main)
                authExplicit()
            }
             fun authExplicit() {
                    CoroutineScope(Dispatchers.Default).launch {
                        try {
                            val credentials =
                                GoogleCredentials.fromStream(resources.assets.open("studentsamplechatbot-xvgloa.json"))
                                    .createScoped(Collections.singletonList("https://www.googleapis.com/auth/dialogflow"))
                            credentials.refreshIfExpired()
                            val accessToken = credentials.accessToken
                            Log.e("log_data", "Token :" + accessToken.tokenValue)
                            if (accessToken.tokenValue.isNotEmpty()) {
                                Log.e(
                                    "log_data",
                                    "Got it --> authenticationType :" + credentials.authenticationType
                                )
                                AuthToken = "Bearer " + accessToken.tokenValue
                            } else {
                                Log.e("log_data", "No token")
                                AuthToken = ""
                            }
                            CoroutineScope(Dispatchers.Main).launch {
                                initViews()
                            }
                        } catch (e: Exception) {
                            Log.e("log_data", e.toString())
                        }
                    }
                }
        }

You can download from Google Cloud Platform

  1. Google Cloud Platform -> Select your Project -> IAM & Admin -> Service accounts -> Create Service Account

  2. Create a Service Account will open one page there are several details that add details and create it.

  3. After Creating a Service account, you can find a created service account on the list.

  4. From the right side, there is actions column is there with three dots with each. from that, there is one option create key. When you click on that it will open one dialog with two options JSON and P12. When you select JSON and click on create, it will download the JSON file of your service account.

  5. You can use this JSON file for your Android project and place it into an assets folder.
    Your Project -> app -> src -> main -> assets

  6. You can use the above function for getting access token.

huangapple
  • 本文由 发表于 2020年4月7日 14:20:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/61073893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定