前台存放项目的client_id和client_secret(从Google官方申请下来的)
同时项目引入gapi包,在全局种下gapi变量
调用全局gapi.auth2.init方法,传入client_id,获取auth2对象。
对auth2对象调用grantOfflineAccess()方法,页面弹出Google登录框。
用户在页面上输入登录账号密码回车,触发grantOfflineAccess()方法的promise回调,resolve里返回code,形如
{code: "4/pAFQK3NDf9Ahu-8-HH11TadgVTC-gGYJPoR-NcG_ylNrbkcAKFU9nZtyKCxLuwKy_Wz7Ow69WO8n2tBhU0XvOiA”}
将code作为参数,redirectUrl作为header,向http层发起Login请求
————————————————————————————————————
http层收到前台传来的redirectUrl和code
引入google-auth-library 调用 OAuth2Client方法,传入后台存的同一套client_id、client_secret,以及redirectUrl,new一个oAuth2Client,得到形如下的对象
oAuth2Client{
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
transporter: DefaultTransporter {},
credentials: {
access_token: 'ya29.GltmB6QfWFAFkl...',
refresh_token: '1/tQ_8vuUvp2astHuOUjMbl3...',
scope: 'openid ' +
'https://www.googleapis.com/auth/userinfo.profile ' +
'https://www.googleapis.com/auth/userinfo.email',
token_type: 'Bearer',
id_token: 'eyJhbGciOiJSUzI1...',
expiry_date: 1566198602524
},
certificateCache: {},
certificateExpiry: null,
certificateCacheFormat: 'PEM',
refreshTokenPromises: Map {},
_clientId: '490136655706-ljvb5j...del9kqum.apps.googleusercontent.com',
_clientSecret: 'qjzBLgt2UdJvA...',
redirectUri: 'http://localhost:8081',
eagerRefreshThresholdMillis: 300000
}
从credentials的字段里取出refresh_token,返回它给到前端。
(本文只讨论Google登录流程。至于前端拿refresh_token怎么用,存在哪儿,以及后台存下refresh_token后的过期操作,不在本文讨论范围内。)