来自Google API的存储凭据可使用Java重复使用 [英] Stored Credential from Google API to be reused using Java

查看:73
本文介绍了来自Google API的存储凭据可使用Java重复使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功授权了我的桌面应用程序.它存储一个名为StoredCredential的文件.为了不必每次运行应用程序时都将URL复制到浏览器,接受等步骤,我想使用已经存储的凭据.

I have successfully authorized my desktop application. It stores a file called StoredCredential. In order to not have to keep doing the copy URL into browser, accept, etc., steps every time I run the app, I want to use the credentials that I already have stored.

到目前为止,我的代码:

My code so far:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport,
    JSON_FACTORY,
    CLIENT_ID,
    CLIENT_SECRET,
    SCOPE)
    .setDataStoreFactory(dataStoreFactory)
    .setApprovalPrompt("auto").setAccessType("offline").build();
//
System.out.println("flow success");     

String url = flow
    .newAuthorizationUrl()
    .setRedirectUri(REDIRECT_URI) 
    .build();

System.out.println("Please open the following URL in your browser then "
    + "type the authorization code:");

System.out.println("  " + url);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String code = br.readLine();

GoogleTokenResponse tokenResponse
    = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();

GoogleCredential credential = new GoogleCredential
    .Builder()
    .setTransport(new NetHttpTransport())
    .setJsonFactory(new JacksonFactory())
    .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
    .addRefreshListener(new CredentialRefreshListener() {
            @Override
            public void onTokenResponse(
                Credential credential,
                TokenResponse tokenResponse) throws IOException {

                System.out.println("Token Refreshed Succesfully");
            }

            @Override
            public void onTokenErrorResponse(
                Credential credential,
                TokenErrorResponse tokenErrorResponse) throws IOException {

                System.out.println("ERROR WITH TOKEN WTF?");
                }})
     .build();

如何读取存储的凭据并绕过命令行提示符?

How do I read the stored credential and bypass the command line prompt?

我在想类似的东西

if (stored cred exists) { 
    try  {
        // use 
    } catch  {
        // prompt the user
    }
}

推荐答案

您可以通过存储的凭据创建GoogleCredential对象,如下所示:

You can create GoogleCredential object from stored credentials like this:

GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(new NetHttpTransport())
        .setJsonFactory(new JacksonFactory())
        .setClientSecrets("client_id", "client_secret")
        .build();

credential.setAccessToken("access_token");

这篇关于来自Google API的存储凭据可使用Java重复使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆