I'am building a react native mobile app with user authentication. I decided to use Firebase auth as it is relatively easy to implement.
I want to use my own backend (node, express) and my own DB (MongoDB) and I need to protect my API calls to check if the user is authenticated and if he has the permission to do the operation.
But I am not at ease with Token validation and I'am not sure I'am doing it the right way...
This is how I am trying to do to make a simple GET or POST request from the client (mobile app):
On the client I retrieve the current User token and send it in the header of my GET request:
firebase.auth().currentUser.getIdToken(true).then(token => {
fetch('http://localhost:3000', {
method: 'GET',
mode: 'cors',
headers: {
'AuthToken': token
}
}).then(res => res.json().then(res => console.log(res)))
.catch(err => console.log(err))
An on the server I use a middleware to check the token thanks to firebase admin
function checkAuth(req, res, next) {
if (req.headers.authtoken) {
admin.auth().verifyIdToken(req.headers.authtoken)
.then((token) => {
console.log(token)
next()
}).catch(() => {
res.status(403).send('Unauthorized')
});
} else {
res.status(403).send('Unauthorized')
}
}
So for a simple get request from a logged user I have to do the following :
- get the user IdToken on client side
- send it to the server
- check it with firebase
- do the operation on my DB
- send the data back to the client
Am I doing it the right way ? I don't know if I should store the IdToken on the phone memory in order to avoid geting it from firebase everytime (but the token expires after 1 hour...)
It seems like a lot of "check from firebase" operation just for simple fetch...
Can you give me some advise on how to make all of this more efficient ?
Thanks a lot !
question from:
https://stackoverflow.com/questions/65877095/use-firebase-for-auth-and-mongodb-for-db 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…