OAuth 2.0 を使用してGoogle の開発者ページで説明されているように、適切なクライアント ID の一意の URL を作成しました。
URL の形式は次のとおりです。
https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
state=%2Fprofile&
redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Foauthcallback&
response_type=token&
client_id=812741506391.apps.googleusercontent.com
ユーザーはログインでき、リダイレクト URL にリダイレクトされますが、問題は、jquery を使用して応答を解析しようとすると、成功ではなく失敗することです。
リダイレクト URL ページで次の JavaScript を使用しています。
<script>
// First, parse the query string
var acc_token;
var params = {}, queryString = location.hash.substring(1),
regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
if(m[1]=="access_token")
acc_token = m[2];
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// And send the token over to the server
var req = new XMLHttpRequest();
// consider using POST so query isn't logged
req.open('GET', 'https://' + window.location.host + '/catchtoken?' + queryString, true);
req.onreadystatechange = function (e) {
if (req.readyState == 4) {
if(req.status == 200){
window.location = params['state']
}
else if(req.status == 400) {
// alert('There was an error processing the token.')
}
else {
// alert('something else other than 200 was returned')
}
}
};
req.send(null);
$.ajax({
type: 'GET',
url:"https://www.googleapis.com/oauth2/v1/userinfo?access_token="+acc_token,
datatype : "json",
success : function(data)
{
console.log(data);
},
error : function()
{
alert("Failure!");
}
});
</script>
JavaScript は正常に動作しています。変数へのアクセス トークンを取得できます。次に、URL https://www.googleapis.com/oauth2/v1/userinfoを使用して Google サーバーに GET リクエストを送信します。 jquery ajaxですが、エラー関数になります。access_token リクエストを使用して手動で URL を実行すると、ユーザーのすべての詳細を含む json 配列が返されます。また、データ型をjsonpに変更しようとしましたが、役に立ちませんでした。
この方法が不可能な場合は、ユーザー情報を取得するための応答を処理する方法を誰かが提案できます。サンプルコードも教えてください。