2017-08-11 75 views
1

我想了解使用令牌的Firebase自定義auth方法,但文檔對我來說並不是那麼清楚。之前,我試圖與智威湯遜發電機玩,我想檢查是否有使用的身份驗證響應令牌通過JavaScript登錄web客戶端的方式:Firebase:通過REST獲取令牌並使用signInWithCustomToken

1)首先,在擊:

curl 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=[theapikey]' -H 'Content-Type: application/json' --data-binary '{"email":"[the-user-email]","password":"[the-user-valid-password]","returnSecureToken":true}' 

2)響應:

{ 
"kind": "identitytoolkit#VerifyPasswordResponse", 
"localId": "<theresponse-localid>", 
"email": "<theresponse-user-email>", 
"displayName": "<theresponse-displayname>", 
"idToken": "<theresponse-idtoken-string>", 
"registered": true, 
"refreshToken": "<theresponse-refreshToken>", 
"expiresIn": "3600" 
} 

3)因此,我的結果複製到一個JavaScript對象:

var token = { 
"kind": "identitytoolkit#VerifyPasswordResponse", 
"localId": "<localid-string>", 
"email": "<user-email>", 
"displayName": "<user-displayname>", 
"idToken": "<idtoken-string>", 
"registered": true, 
"refreshToken": "<refreshtoken-string>", 
"expiresIn": "3600" 
}; 

4)我已經嘗試了每一種嘗試使用該令牌進行驗證:

firebase.auth().signInWithCustomToken(token).catch(function(error) { 
    console.log("firebase.auth().signInWithCustomToken() Error: "); 
    console.log(error); 
} 

firebase.auth().signInWithCustomToken(JSON.stringify(token)).catch(function(error) { 
    console.log("firebase.auth().signInWithCustomToken() Error: "); 
    console.log(error); 
} 

firebase.auth().signInWithCustomToken(token.idToken).catch(function(error) { 
    console.log("firebase.auth().signInWithCustomToken() Error: "); 
    console.log(error); 
} 

5)對於每一個,我得到同樣的錯誤:

"Object { code: "auth/invalid-custom-token", message: "The custom token format is incorrect", stack: "" }" 

顯然我錯了,但大多數文檔我閱讀描述創建自定義JWT令牌。恐怕我還不明白。

+0

什麼是您的具體問題? –

+0

我希望能夠使用REST api來生成一個令牌,我可以在JavaScript中使用它來使用firebase.auth()來驗證用戶。signInWithCustomToken(令牌) – orellabac

回答

1

如果你想signInWithCustomToken,你需要創建一個用你的私鑰簽名的JWT。在火力地堡管理軟件開發工具包提供該功能:https://firebase.google.com/docs/auth/admin/create-custom-tokens

這將您的服務器上運行,然後您發送自定義的令牌給客戶端並登錄使用:

firebase.auth().signInWithCustomToken(token).catch(function(error) { 
    console.log("firebase.auth().signInWithCustomToken() Error: "); 
    console.log(error); 
}); 
+0

謝謝Bojeil,你是對的。我設法編寫了一個JWT類來生成一個令牌,並且我可以在JavaScript中使用它。我用這篇文章作爲參考:https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library – orellabac

+0

很酷,很高興我能夠提供幫助。 – bojeil

相關問題