最近需要在部署的接口平台上支持Google账号登录功能,过程中遇到了不少问题,在此记录一下
官方文档:https://developers.google.com/identity/gsi/web/guides/client-library?hl=zh-cn
1.创建凭据
首先需要到Google Cloud创建凭据,具体创建过程就不再赘述了,这个是比较简单的,注意本地调试时需要同时添加 http://localhost
和 http://localhost:<port_number>
2.代码实现
2.1.代码集成
vue中使用下面的方法加载客户端库并集成登录按钮
<div class="g-signin-button">
<component :is="'script'" src="https://accounts.google.com/gsi/client" ansyc/>
<div id="g_id_onload"
data-client_id="YOUR CLIENT_ID"
data-context="signin"
data-ux_mode="popup"
data-callback="googleSignCallBack"
data-auto_prompt="false">
</div>
<div class="g_id_signin"
data-type="standard"
data-shape="pill"
data-theme="outline"
data-text="signin_with"
data-size="large"
data-logo_alignment="left">
</div>
刷新页面即可看到出现登录按钮
2.2.获取用户信息
在回调方法中获取登录用的凭证,并发送给后台
googleSignCallBack (googleUser) {
let credential = googleUser.credential;
this.result = this.$post("/googleLogin", credential, response => {
});
},
后台使用Google API 客户端库验证凭据,需添加Maven依赖
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.32.1</version>
</dependency>
验证凭证获取用户信息
@PostMapping(value = "/googleLogin")
public ResultHolder googleLogin(@RequestBody String token){
ResultHolder result = null;
try {
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory())
.setAudience(Collections.singletonList(googleClientId))
.build();
GoogleIdToken idToken = verifier.verify(token);
if (idToken != null){
GoogleIdToken.Payload payload = idToken.getPayload();
String email = payload.getEmail();
String name = (String) payload.get("name");
//处理流程
}
}catch (Exception ex){
ex.printStackTrace();
}
return result;
}
3.问题记录
3.1.报错[GSI_LOGGER]: The value of 'callback' is not a function
Google的 data-callback
属性需要一个全局函数作为回调函数,而不能直接绑定到 Vue 组件的方法上,需要在 mounted
函数中,将 Vue 组件的方法 googleSignCallBack
赋值给一个全局变量或全局对象的属性,使它在全局范围内可访问