Google API调用方式总结——前端js调用和后端各种语言调用

实习期间接到需求,期望能在.net框架下的前端调用google drive api,并持有access_token和refresh_token以保持和google api的长时间连接(单独acccess_token只能维持3600秒访问时间)。

然而亲测前端使用纯js调用gapi只能获得access_token,无法同时得到refresh_token,最接近成功的方法如下:

GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.grantOfflineAccess().then((res) => {
                        var code = res.code;
                        window.code = code;
                    });

得到authorization code可以传给后端从而通过其他语言的api获得两个token,意味着google不建议在前端暴露的太多,想获得两个token需要将cuthorization code传到后端,然后通过各种api获取refresh_token。当然,由于后端发送请求没有跨域问题,也可以直接访问https://accounts.google.com/o/oauth2/token,请求方法为POST,如下:

https://accounts.google.com/o/oauth2/token code={AuthCode}&
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&
redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code

其实后端api也是对这个方法的封装。

发布了71 篇原创文章 · 获赞 31 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/m0_37828249/article/details/81540985