使用Google API Java客户端库刷新令牌 [英] Refresh Token with Google API Java Client Library

查看:97
本文介绍了使用Google API Java客户端库刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google API Java客户端 http://code. google.com/p/google-api-java-client/并能够成功获取Android的访问令牌.

I'm using the Google API Java Client http://code.google.com/p/google-api-java-client/ and am able to get the access token successfully for Android.

    // Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, CalendarScopes.CALENDAR);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

由于我希望Web服务器进行离线API调用,因此我需要刷新令牌.我已经进行了广泛的搜索,还没有弄清楚该怎么做.

As I'd like my web server to make offline API calls, I need a refresh token. I have been searching extensively and have not yet figured out how to do so.

理想情况下,我希望通过WebView使用Google API Java客户端来获取刷新令牌(无需输入用户名或密码).

Ideally, I'd prefer to use the Google API Java Client over the WebView to grab the refresh token (no need to enter a username or password).

任何帮助将不胜感激!

推荐答案

您还可以通过创建配置为OAuth 2.0客户端ID的刷新令牌来做到这一点.

You can also do this by creating a refresh token configured to a OAuth 2.0 Client Id.

转到 https://console.developers.google.com/apis/credentials

  1. 点击创建凭据".
  2. 点击"OAuth客户端ID".
  3. 选择"Web应用程序">给个名字.
  4. 在授权重定向URI"中添加 https://developers.google.com/oauthplayground .
  5. 点击创建.
  1. Click 'Create Credential'.
  2. Click 'OAuth client Id'.
  3. Select 'Web application' > Give a name.
  4. Add https://developers.google.com/oauthplayground to 'Authorized redirect URIs'.
  5. Click Create.

下一步将需要ClientId和Secret.

You will need the ClientId and the Secret for next steps.

然后转到 https://developers.google.com/oauthplayground/

  1. 单击右上角的"AOuth 2.0配置".
  2. 选中使用您自己的OAuth凭据".
  3. 使用上面创建的OAuth 2.0凭据的客户端ID和密码更新"OAuth客户端ID"和"OAuth客户端密码".
  4. 在左上角的第1步中,选择所有必要的范围.(请注意,请求中不匹配的范围将返回'invalid_scopes'.)
  5. 点击授权API".这会将您重定向到允许权限的同意页面.
  6. 在步骤2中,点击交换令牌的授权代码"
  7. 您将获得带有刷新令牌的访问令牌.下一步,我们将需要此刷新令牌.

您可以使用此访问令牌对在范围中指定的服务进行身份验证. 除非访问令牌不与OAuth 2.0客户端绑定,否则访问令牌的寿命很短,并且刷新令牌会在24小时后过期(我们只是将刷新令牌的作用持续到用户撤销或由于6个月的不活动时间而终止).

You can use this access token to authenticate to services you specified in scopes. Access Tokens are short lived and Refresh tokens expire after 24 hours unless it is not bound to a OAuth 2.0 client (We just made our refresh token to last until it is revoked by the user or expires due to 6 months inactivity).

您需要在访问令牌过期之前刷新访问令牌.查看以下示例以了解操作方法.

You need to refresh the Access Token before it expires. Check out following example to see how.

public String getNewToken(String refreshToken, String clientId, String clientSecret) throws IOException {
        ArrayList<String> scopes = new ArrayList<>();

        scopes.add(CalendarScopes.CALENDAR);

        TokenResponse tokenResponse = new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),
                refreshToken, clientId, clientSecret).setScopes(scopes).setGrantType("refresh_token").execute();

        return tokenResponse.getAccessToken();
}

上面示例中的

clientId和clientSecret指的是OAuth 2.0客户端凭据.

clientId and clientSecret in above example refers to OAuth 2.0 client credentials.

您可以像这样创建一个"GoogleCredential"

You can create a 'GoogleCredential' with that like this

public Credential getCredentials() throws GeneralSecurityException, IOException, FileNotFoundException {
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    // Load client secrets.
    String CREDENTIALS_FILE_PATH = "/credentials.json"; //OAuth 2.0 clinet credentials json
    InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    String clientId = clientSecrets.getDetails().getClientId();
    String clientSecret = clientSecrets.getDetails().getClientSecret();

    GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(HTTP_TRANSPORT)
            .setJsonFactory(JSON_FACTORY)
            .setClientSecrets(clientId, clientSecret)
            .build();

    String refreshToken = "<REFRESH-TOKEN>"; //Find a secure way to store and load refresh token
    credential.setAccessToken(getNewToken(refreshToken, clientId, clientSecret));
    credential.setRefreshToken(refreshToken);

    return credential;
}

这篇关于使用Google API Java客户端库刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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