[英]AWS Amplify: After confirmSignUp, what is the best practice to automatically Sign In a user?
[英]What Sign in method to use best?
我們有一個 flutter 應用程序(ios、android、web),用戶通過用戶名和密碼登錄。 我們還使用 google firebase,因為它功能強大且易於集成。
用戶名和密碼主要屬於我們收集數據的網站。 (例如 - 如果他們在沒有應用程序的情況下使用網站,並且他們更改了密碼,之后他將無法登錄該應用程序)
現在提到的網站主機給我們 API 訪問權限,通過 OpenId 登錄以獲取 API 的訪問令牌。因為我們也存在安全風險,因為我們也存儲了用戶的密碼!
對於 API 訪問,我們真的不需要存儲用戶的用戶名和密碼,因為它們是多余的。 但是如果我們想添加一個功能(例如消息發送或進一步的數據存儲),我們需要讓用戶登錄到 firebase。
到目前為止,我們正在使用 for (first) signin 下面的代碼片段:
firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
對於已經登錄的用戶:
firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
請注意,類似的憑據也用於登錄 API。(因為用戶已經在那里注冊)
我們如何才能使用上述信息登錄 firebase 而無需兩次詢問密碼和用戶名(一次用於我們,一次用於 API)?
我們已經嘗試過:
await firebaseAuth.signInWithCustomToken(token)
使用來自 OpenId 的 jwl 令牌,當然它不起作用,因為該令牌不包含 uid 引用。
解決方案
創建一個 Firebase Cloud Function 就像Firebase Cloud Functions中描述的那樣。
請注意,如果您想創建自定義令牌,雲函數需要權限。 在 initializeApp(..)
admin.initializeApp({
serviceAccountId: '{App_Name}@appspot.gserviceaccount.com',
});
所以要選擇正確的服務賬號,你還要給他生成token的權限。 (參見 => Stackoverflow 問題
雲 Function 看起來如下所示:
export const functionName= functions.https.onRequest(async (request, response) => {
const id = request.query.id;
const passcode = request.query.passcode; // not really needed
// add other passcodes for different authentications
if (passcode == "{COMPARE SOMETHING}") {
await admin.auth().createCustomToken(id).then((customToken) => {
response.status(200).send({
'id': id,
'customToken': customToken
});
}).catch((error) => {
response.status(500).send({
'ErrorMessage': "No token could be generated",
"Error": error
});
});
}
else {
response.status(500).send({
'ErrorMessage': "Passcode wrong"
});
}
});
另一方面,我們在移動應用程序上有代碼:
// Get JWT Token
Map<String, dynamic> jwtpayload =
Jwt.parseJwt(response_decoded['id_token']); // use import 'package:jwt_decode/jwt_decode.dart';
final queryParameters = {
'id': jwtpayload ['sub'],
'passcode': 'APassCode',
};
final uri = Uri.https('us-central1-{yourApp}.cloudfunctions.net',
'/{functionName}', queryParameters);
final cloud_function_api_call = await client.post(uri);
var decoded_cloud_function_api_call =
jsonDecode(cloud_function_api_call.body);
最后:
await firebaseAuth.signInWithCustomToken(
decoded_cloud_function_api_call['customToken']);
我希望它能幫助其他面臨類似問題的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.