Reputation: 25396
I have an angular app that uses firebase to authenticate users on the client. This seems to work properly.
export class AuthService {
user$: Observable<firebase.User>;
constructor(private af_auth: AngularFireAuth) {
this.user$ = this.af_auth.authState;
this.user$.subscribe(user => {
// do something with the firebase user
});
}
}
I also have some server-based stuff running in node.js with express. I would like to try to verify that the user hitting my endpoint is already authenticated with my app through firebase. Can I do this?
I'd like to have a route handler in express something like this:
var firebase_app = firebase.initializeApp(firebase_config);
auth.isAuthenticated = function (req, res, next) {
// I had seen a suggestion to do the following, but currentUser is always null here.
var user = firebase_app.auth().currentUser;
if (user !== null) {
// Authenticated with my app?
req.auth_user = user;
next();
} else {
res.status(401).send({error: 'Nope'});
}
};
How can I tell from within the express route handler that my user is logged in to my app?
Upvotes: 2
Views: 935
Reputation: 9308
Step 1 Angular. Send the Firebase Auth ID token in the header from angular to your express endpoint.
postRequest() {
const url = 'https://your-endpoint';
firebase.auth().currentUser.getIdToken()
.then(authToken => {
const headers = new Headers({'Authorization': 'Bearer ' + authToken });
return this.http.post(url, { someData } , { headers }).toPromise()
})
}
Step 2 Node. Decrypt the the auth token using the Firebase admin SDK. verifyIdToken
verifies the Firebase ID token (JWT). If the token is valid, the promise is fulfilled with the token's decoded claims; otherwise, the promise is rejected.
const admin = require('firebase-admin');
admin.initializeApp(yourConfig);
const express = require('express')
const app = express()
app.post('/your-endpoint', (req, res) => {
const token = req.headers.authorization.split('Bearer ')[1]
return admin.auth().verifyIdToken(token)
.then(decodedToken => {
const uid = decodedToken.uid;
res.status(200).send('Looks good!')
})
.catch(err => res.status(403).send('Unauthorized'))
});
Sources:
https://firebase.google.com/docs/auth/admin/verify-id-tokens https://angularfirebase.com/lessons/secure-firebase-cloud-functions/
Upvotes: 3