如何为 S3 访问刷新 google+ 授权令牌

How to refresh google+ auth token for S3 access

我有一个使用 cordova-plugin-googleplus to allow users to authenticate with their google+ account. The app also gives the user access to an S3 bucket to upload photos via the aws sdk. To make this happen we are using AWS Cognito with federated identities 的 cordova 应用程序,效果很好。

问题是 1 小时后没有 S3 activity,下次应用尝试上传时我开始收到此错误:

{
    "__type": "NotAuthorizedException",
    "message": "Invalid login token. Token expired: 1513206998 >= 1513197640"
}

根据我的 research,问题是 google+ 令牌即将到期,需要刷新,但我无法理解如何操作。请注意,这需要在用户不知情的情况下在后台完成。要求用户每小时重新进行身份验证是不可接受的。

这里是登录码:

window.plugins.googleplus.login(prams, obj => {
    let authData = {
        accessToken: obj.accessToken,
        idToken: obj.idToken
    };

    localStorage.setItem('authData', authData);
});

那么我们是时候访问 S3 存储桶了:

let authData = localStorage.getItem('authData');

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'my-cognito-identity-pool-id',
    Logins: { 'accounts.google.com': authData.idToken };
});

AWS.config.region = 'us-west-2;

AWS.config.credentials.getPromise()
    .then(() => {
        let s3 = new AWS.S3();

        let params = {
            Bucket: 'my-bucket',
            Key: 'my-key',
            Body: imageBytes,
            ContentType: 'image/jpeg'
        };

        s3.upload(params);
    });

我的理解是我需要查找上面列出的错误并在出现时刷新 google+ 令牌,但我不确定如何完成。我在 cordova-plugin-googleplus 库中没有看到对此的支持。我必须自己发出http请求吗?这是如何运作的?大概我需要在登录后保存刷新令牌并以某种方式使用它。

根据this

You need to take the oauth token and exchange it for the correct tokens (refresh/ access) on login

[...]

When a user needs their token refreshed (after 60 minutes) you must refresh it for them. Aka when you request a google api service and it sends you back a "token is invalid", you must eat the error and refresh the token and try the original request again.

如果使用 oauth2/v4 端点的令牌仍然无效,则可能必须使用 oauth2/v1 端点:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=...

你也可以看看google documentation and also you can find a php example here

我能够通过使用 trySilentLogin method that comes with cordova-plugin-googleplus.

来让它工作