Google身份验证API(Google Identity API)是Google提供的一套OAuth 2.0认证服务,允许开发者安全地获取用户授权并访问Google账户信息,包括Gmail地址。
首先需要在Google Cloud Platform控制台创建项目并启用相关API:
创建OAuth客户端ID,配置授权域名和重定向URI。
以下是使用JavaScript实现的示例代码:
// 加载Google API客户端库
function loadGoogleAuth() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
scope: 'profile email'
});
});
}
// 登录并获取用户信息
function signIn() {
const auth2 = gapi.auth2.getAuthInstance();
auth2.signIn().then(function(googleUser) {
const profile = googleUser.getBasicProfile();
console.log('Email: ' + profile.getEmail());
}).catch(function(error) {
console.error('Error signing in: ', error);
});
}
如果需要服务器端验证,可以使用ID token:
// 前端获取ID token
const id_token = googleUser.getAuthResponse().id_token;
// 后端验证示例(Node.js)
const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(YOUR_CLIENT_ID);
async function verifyToken(idToken) {
const ticket = await client.verifyIdToken({
idToken: idToken,
audience: YOUR_CLIENT_ID,
});
const payload = ticket.getPayload();
const email = payload['email'];
console.log('Verified email:', email);
return email;
}
获取用户邮箱需要请求以下scope之一:
email
- 仅获取邮箱地址profile
- 获取基本资料(包括邮箱)https://www.googleapis.com/auth/userinfo.email
- 明确请求邮箱权限原因: 可能没有请求正确的scope或用户没有授予权限
解决: 确保请求了email
或profile
scope,并检查用户授权界面是否显示邮箱权限
原因: 用户可能使用Google账户关联的其他邮箱登录 解决: 这是正常现象,Google账户可以关联任意邮箱地址
原因: 可能是重定向URI配置不正确或客户端ID无效 解决: 检查Google Cloud控制台中的OAuth客户端配置
通过以上方法,您可以安全可靠地获取用户的Gmail地址。