React Native Firebase:如何检查授权?
调用“createUserWithEmailAndPassword”或“signInWithEmailAndPassword”后,属性“currentUser”将填入“auth()”。重新启动应用程序后,即使我从Firebase控制台中删除此用户,它仍将保持完整状态 当应用程序启动时,如何检查用户的授权?要强制客户端“签入”服务器,您可以通过调用React Native Firebase:如何检查授权?,firebase,react-native,firebase-authentication,Firebase,React Native,Firebase Authentication,调用“createUserWithEmailAndPassword”或“signInWithEmailAndPassword”后,属性“currentUser”将填入“auth()”。重新启动应用程序后,即使我从Firebase控制台中删除此用户,它仍将保持完整状态 当应用程序启动时,如何检查用户的授权?要强制客户端“签入”服务器,您可以通过调用firebase.auth().currentUser.getIdToken(true)来使用该方法。如果用户已被删除,则应拒绝,错误代码为'auth/
firebase.auth().currentUser.getIdToken(true)
来使用该方法。如果用户已被删除,则应拒绝,错误代码为'auth/user token expired'
从中,我将使用此作为MWE的基础:
import React,{useState,useffect}来自“React”;
从“react native”导入{View,Text};
从'@react native firebase/auth'导入身份验证;
函数App(){
//在Firebase连接时设置初始化状态
const[initializing,setInitializing]=useState(true);
const[user,setUser]=useState();
//处理用户状态更改
函数onAuthStateChanged(用户){
setUser(用户);
if(初始化)setInitializing(false);
}
useffect(()=>{
const subscriber=auth().onAuthStateChanged(onAuthStateChanged);
返回订阅服务器;//卸载时取消订阅
}, []);
如果(初始化)返回null;
如果(!用户){
返回(
登录
);
}
返回(
欢迎{user.email}
);
}
一旦用户登录或其缓存访问被恢复,onAuthStateChanged
将收到当前用户对象的事件。这里我们添加ID令牌请求
AuthStateChanged上的函数(用户){
如果(!用户){
//未登录
setUser(用户);
if(初始化)setInitializing(false);
返回;
}
user.getIdToken(/*forceRefresh*/true)
。然后(令牌=>{
//如果在此处,此用户仍被授权。
setUser(用户);
if(初始化)setInitializing(false);
},错误=>{
如果(error.code==='auth/user令牌已过期'){
//令牌无效。onAuthStateChanged所需的任何操作都不会以null再次激发
}否则{
console.error('意外错误:'+错误代码);
}
});
}