我正在使用适用于Android的Google身份工具包,为我的应用程序用户提供一种无需记住新密码即可进行注册/登录的方法,并且可以免除安全保存所有密码的麻烦。
这是我在Android上的代码,基本上将带有POST的IdToken字符串发送到我的Node.js服务器。完美运行,IdTokenString通过https发送到我的服务器。
// Step 1: Create a GitkitClient.
// The configurations are set in the AndroidManifest.xml. You can also set or overwrite them
// by calling the corresponding setters on the GitkitClient builder.
//
client = GitkitClient.newBuilder(this, new GitkitClient.SignInCallbacks() {
// Implement the onSignIn method of GitkitClient.SignInCallbacks interface.
// This method is called when the sign-in process succeeds. A Gitkit IdToken and the signed
// in account information are passed to the callback.
@Override
public void onSignIn(IdToken idToken, GitkitUser user) {
showProfilePage(idToken, user);
// Now use the idToken to create a session for your user.
// To do so, you should exchange the idToken for either a Session Token or Cookie
// from your server.
// Finally, save the Session Token or Cookie to maintain your user's session.
final JSONObject sendJson = new JSONObject();
try {
sendJson.put("tokenString", idToken.getTokenString());
} catch (JSONException ex) {
ex.printStackTrace();
}
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg) {
try {
//Retrieve the logintoken from the server
HttpUtils.postSecure(Util.Constants.httpsServerUrl + "/registerwithtoken", sendJson.toString().getBytes("UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void nothing) {
}
}.execute();
在我的Node.js服务器上,我使用以下代码检索IdToken字符串:
function registerWithToken(req, res) {
var tokenString = req.body.tokenString;
if(typeof tokenString == "undefined") {
res.status(500).send('Tokenstring is undefined!');
}
console.log("INCOMING REGISTER WITH TOKEN");
console.log(req.body);
var decodedJWT = jwt.decode(tokenString, {complete: true});
var idToken = decodedJWT.payload.toString();
console.log(idToken);
gitkitClient.verifyGitkitToken(idToken, function (err, resp) {
if (err) {
console.log("INVALID TOKEN!! "+err);
res.status(500).send('Invalid token: ' + err);
} else {
//valid token!
console.log("VALID TOKEN SEND JWT BACK TO ANDROID");
}
});
}
我的问题是,node.js gitkitClient总是返回Token无效,但我不知道为什么。
我的idToken似乎是正确的:
{ iss: 'https://identitytoolkit.google.com/',
aud: '*devConsoleNumbers*.apps.googleusercontent.com',
iat: 1449712391,
exp: 1450921991,
user_id: '*numbers*',
email: '*mail*',
provider_id: 'google.com',
verified: true,
display_name: '*John Doe*' }
错误行将打印到控制台:
INVALID TOKEN!! Unable to verify the ID Token: Wrong number of segments in token: [object Object]
我不知道为什么验证失败。
有解决这个问题的方法吗?
最佳答案
gitkitClient.verifyGitkitToken()期望将原始令牌字符串作为第一个参数:
gitkitClient.verifyGitkitToken(req.body.tokenString,函数(err,resp){...});