问题描述
我试图通过在 People Api 请求中指定 here 中的“地址”字段来获取经过身份验证的用户的国家/地区。 这是代码:
router.post("/test_scope",(req,res) => {
const { idToken,accesstoken } = req.body;
authenticationServices
.validateGoogleAccesstoken(idToken,accesstoken)
.then((response) => {
res.json(response);
});
});
const validateGoogleAccesstoken = async (idToken,accesstoken) => {
try {
const CLIENT_ID =
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com";
const client = new oauth2client(CLIENT_ID);
const ticket = await client.verifyIdToken({
idToken,audience: CLIENT_ID,});
const payload = ticket.getPayload();
const { OAuth2 } = google.auth;
const oauth2client = new OAuth2();
oauth2client.setCredentials({ access_token: accesstoken });
const peopleAPI = google.people({
version: "v1",auth: oauth2client,});
const { data } = await peopleAPI.people.get({
resourceName: "people/me",personFields: "birthdays,genders,addresses",});
const { birthdays,addresses,ageRanges } = data;
return data;
} catch (error) {
console.log("error: ",error);
throw new Error("Google token validation Failed");
}
};
我已经在我用来登录的帐户中设置了 addresses information,如下所示:
这是我发送请求后得到的整个响应:
{
"resourceName": "people/XXXXXXXXXXXXXXXXx","etag": "%XXXXXXXXXXXXXXXXXXXXXXXXXX","genders": [
{
"Metadata": {
"primary": true,"source": {
"type": "PROFILE","id": "XXXXXXXXXXXXXXXXXXXX"
}
},"value": "female","formattedValue": "Female"
}
],"birthdays": [
{
"Metadata": {
"primary": true,"id": "1XXXXXXXXXXXXXXXXXXXXXXXX"
}
},"date": {
"month": 8,"day": 9
}
},{
"Metadata": {
"source": {
"type": "ACCOUNT","id": "XXXXXXXXXXXXXXXXXXXXXXx"
}
},"date": {
"year": 1996,"month": 8,"day": 9
}
}
],"addresses": [
{
"Metadata": {
"primary": true,"source": {
"type": "PROFILE","id": "111110367350060808978"
}
},"formattedValue": "XXXXXXXXXXXXX,XXXXX,XXXXX","type": "home","formattedType": "Home"
}
],}
如您所见,“地址”中缺少国家/地区字段。
注意:在用户点击登录按钮后,我正在从前端检索 idToken
和 accesstoken
:
import GoogleLogin from "react-google-login";
export class LoginPage extends Component {
onGoogleSignInSucceeded(response) {
const { accesstoken,tokenId } = response;
}
render() {
const { errors } = this.state;
return (
<>
<GoogleLogin
clientId="XXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com"
scope="https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/user.gender.read https://www.googleapis.com/auth/user.addresses.read"
// IMPORTANT
// https://developers.google.com/people/api/rest/v1/people/get#authorization-scopes
buttonText="Sign-in with your Google account"
onSuccess={this.onGoogleSignInSucceeded}
onFailure={this.onGoogleSignInFailed}
cookiePolicy={"single_host_origin"}
/>
</>
);
}
}
解决方法
地址字段上的所有字段都是可选的 (see docs)。这也包括国家。也无法保证数据实际上是正确的(用户可以将无效数据添加到他们的 Google 个人资料中),因此请注意这一点并检查 verified
元数据 (see docs)。
话虽如此,您可以尝试使用地理编码 API 从格式化地址中获取国家/地区。这可以通过使用反向地理编码查询 (Google Geocoding API documentation) 来实现。
另请注意,还有其他字段可能包含地址。例如,locations
(see docs) 可以包含有关他们居住地的信息。