Google的第三方登录,简单的记录一下。
配置 Google Cloud Platform
首先访问 Google Cloud Platform 控制台
地址:https://console.cloud.google.com/projectselector2/home
OAuth 同意屏幕
在左边的侧边栏中选择 API和服务
网域验证
凭据
客户端ID用户用户登录,密钥用于服务器验证Token是否有效以及获取用户信息
获取登录地址
Google的文档其实写的很清楚了:传送门
生成临时的用户ID主要是为了识别触发OAuth登录的用户。这里最好还是后端服务器生成。
主要说的是如何生成Google的登录链接,下面是一个生成好的IdToken 给到服务端 大功告成。
eyJhbGciOiJSUzI1NiIsImtpZCI6ImQ0ZTA2Y2ViMjJiMDFiZTU2YzIxM2M5ODU0MGFiNTYzYmZmNWE1OGMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI1ODQxNzk2NTc0MzgtcGVmNW9kb2dlbmppMGhuNDR0dHQ4dmdjN2dxcWgxbXMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI1ODQxNzk2NTc0MzgtaGw5ZHQwZGR1a2VtYTJwdWwwazlhbG10aWh0NHZyZ24uYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMTgzNzU4NzAzMjI2NjExMDA3OTAiLCJlbWFpbCI6ImFzNzUyNDk3NTc2QGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJpYXQiOjE2Mzc4Mjg5MTUsImV4cCI6MTYzNzgzMjUxNX0.C4rlebGZusEO79lapKm4vZsWLaxpY8iG8iqmVF_JhiCwmYEYdqhYdtujeZ7P_og_8ldExQ9GuJO0mSWf-jkjPZyVO5zDVApSr3dgJ8tMR5_vLLQwFl0KCjTemwUvKmbKssO67y8xOqhwvqG53Ss0FK8PpIOM0m6bUlI8fEhrqmBRynrXEl8VwVZC9jRq4q-iMmG9svq8V_pmkvMnFxnyy3uVpjIYP8qpcaPpqk7lMle7MGsrBzCYuOaT3aPVb3LNnTDsQNRZt-PHfcOiijb7rTW0yTI1XJh23tb3zLg_jmeqjDP_tlDSiUk1_c2Rb5zbPAQj_6MJnpbsyt362NqgCw
后端GET这个地址,获取用户的邮箱:
https://www.googleapis.com/oauth2/v2/userinfo
?access_token=ya29.a0AfH6SMB3rFcyq-d8NW3IlCriJvdpPCNBqZvnoKrrcDipoP9A234KtdKpDdXbyzOVp_1PbLbyIMjO5Hx5c_vm0A9PWDTIfXfmwVsugPlUp8VcRCNHnsXVwds2GT
通过令牌可以获取用户的信息,比如邮箱,昵称,头像等等
{
"id": "XXXXXXXXXXXXXXXXX",
"email": "dingzd1995@gmail.com",
"verified_email": true,
"picture": "https://lh3.googleusercontent.com/a-/AOh14GjW7-O4rqIeKtGB_rorN6KIDYd6fRzaEaPYPoKV=s96-c"
}
OK,到这步,就直接根据邮箱和id,来建立对应的账号关系就可以了~
关键代码
private void onGoogleSignInClicked() { Intent intent = mSignInClient.getSignInIntent(); startActivityForResult(intent, RC_SIGN_IN); }
if (requestCode ==RC_SIGN_IN) {
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
Toast.makeText(this , account.getIdToken(),Toast.LENGTH_LONG).show();
String s = account.getIdToken();
((EditText) findViewById(R.id.edit_text_email)).setText( s);
}catch (ApiException e) {
Toast.makeText(this , "失败" ,Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}