As a newbie to web development I'm trying to achieve the following in our Vue.js web app:
Sign in users with their active directory credentials
Use the Firebase Realtime Database to store data and see in the "Authentication" section in the Firebase console who logged on and when
To get this to work I followed the Firebase docs:
Install Firebase in the project and add the "Microsoft" "Sign in method" with the correct "Client ID" and "Client Secret" to the Firebase console.
Client ID:
Client secret:
Firebase console "Authentication"
In Azure App Registration we also added the "Redirect URI" as advised by Firebase:
In our project we created a "firebase.js" file:
import * as firebase from "firebase/app"
import "firebase/auth"
var firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID
}
let firebaseApp = firebase.initializeApp(firebaseConfig)
let provider = new firebase.auth.OAuthProvider('microsoft.com');
export { firebaseApp, provider }
And a Vue component with only 2 buttons:
<template>
<q-page padding>
<h3>Home</h3>
<p>Access token: {{ OAuthAccessToken }}</p>
<p>User details: {{ user }}</p>
<div>
<q-btn color="primary" #click="login"> Login </q-btn>
<q-btn color="primary" #click="logout" class="q-ml-xl"> Logout </q-btn>
</div>
</q-page>
</template>
<script>
import { firebaseApp, provider } from "boot/firebase";
export default {
name: "PageHome",
data() {
return {
OAuthAccessToken: ""
};
},
computed: {
user() {
// return 'test user'
let test = firebaseApp.auth().currentUser;
console.log("user ", test);
return test;
}
},
methods: {
login() {
firebaseApp.auth().signInWithRedirect(provider)
},
logout() {
firebaseApp
.auth()
.signOut()
.then(function() {
console.log("logout succes");
})
.catch(function(error) {
console.log("logout fail");
});
}
},
components: {},
mounted() {
firebaseApp
.auth()
.getRedirectResult()
.then(function(result) {
if (result.credential.accessToken) {
this.OAuthAccessToken = result.credential.accessToken;
console.log("token ", result.credential.accessToken);
}
})
.catch(function(error) {
console.log("fail ", error);
});
}
};
</script>
When clicking the login button we are correctly redirected to the Microsoft sign in page, and we can sign in correctly with our AD credentials. After that we're also correctly redirected back to the app. So that part works fine. However, The following error is displayed in the console:
We tried generating a new secret in the "Azure App Registration" and use that but the issue remains. Are we missing something super obvious here?
Thank you for your help.
let provider = new firebase.auth.OAuthProvider('microsoft.com');
provider.setCustomParameters({
prompt: "consent",
tenant: "the tenant id provided by outlook",
})
This will force the user to select the account to sign in has, and then enter their password. You can find the tenant [Directory (tenant) ID] the same place you got the client ID. Hope this helps, Because I legit had the same problem and found the solution by trying a couple things.
Related
I am trying to add Cloud messaging feature in my project but facing this messaging.getToken() error which I am trying to solve from last 6 hours. Please help.
Thank you
== file firebase.js
import { getMessaging, getToken } from "firebase/messaging";
export const requestPermission = () => {
Notification.requestPermission()
.then( permission => {
if (permission === 'granted') {
messaging.getToken()
.then(currToken => console.log(currToken))
.catch(err => console.log(err))
}
})
.catch(err => console.log(err))
}
== file main.js
<button onClick={requestPermission}>
<p> New Task </p>
</button>
== file firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/6.2.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.2.3/firebase-messaging.js');
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "My api key",
authDomain: "my domain name",
projectId: "my project id",
storageBucket: "my storage bucket address",
messagingSenderId: "id",
appId: "my app Id"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firebase Cloud Messaging
export const messaging = getMessaging();
export default app;
I have followed the steps according to the firebase docs and also one video on youtube, but still have this error TypeError: WEBPACK_IMPORTED_MODULE_2__.messaging.getToken is not a function
I have a problem:
I want a logged in user to be able to use my getRealtimeUsers function. But I get the following error: FirebaseError: Missing or insufficient permissions.
Below you will find the code. Some explanations:
On the React side, I created a firebase, registered a getRealtimeUsers function there, and tried to use it.
firebase.js file
import firebase from "firebase/app";
import "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
};
firebase.initializeApp(firebaseConfig);
export default firebase;
A function that uses the firebase I created:
import firebase from '../../firebase';
export const getRealtimeUsers = () => {
return async () => {
const db = firebase.firestore();
const unsubscribe = db.collection("users")
return unsubscribe;
}
}
Testing of the function
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getRealtimeUsers } from '../redux/actions/chatActions';
import firebase from '../firebase';
let unsubscribe;
class chat extends Component {
componentDidMount() {
unsubscribe = this.props.getRealtimeUsers()
.then(unsubscribe => {
return unsubscribe;
}).catch(error => {
console.log(error);
});
}
componentWillUnmount() {
return () => {
unsubscribe.then(f => f()).catch(error => console.log(error));
}
}
render() {
const ref = firebase.firestore().collection("users");
return (
<div>
check if works
</div>
);
}
}
const mapStateToProps = (state) => ({
});
export default connect(
mapStateToProps,
{
getRealtimeUsers
}
);
Here I let the user do the login
login.js action
export const loginUser = (userData) => (dispatch) => {
axios
.post('/login', userData)
.then((res) => {
console.log(res)
setAuthorizationHeader(res.data.token);
})
.catch((err) => {
console.log(err)
});
};
The login is done on the nodejs side, which is also where I set it to firebase:
const config = {
apiKey: "WqcVU",
authDomain: "c468.firebaseapp.com",
projectId: "c468",
storageBucket: "c468.appspot.com",
messagingSenderId: "087",
appId: "1:087:web:c912",
measurementId: "G-SQX1"
};
;
const firebase = require("firebase");
firebase.initializeApp(config);
// Log user in
exports.login = (req, res) => {
const user = {
email: req.body.email,
password: req.body.password,
};
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
console.log(JSON.stringify(data));
return data.user.getIdToken();
})
.catch((err) => {
console.error(err);
});
};
app.post('/login', login);
the rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
I want only a logged in user to use the getRealtimeUsers function, but even if the user is logged in it doesnt work. That's my problem.
I do not know at all how to solve it
Your case is really problematic, the only way to do security in rules is to access your correntUser or auth. Because you connect through the nodejs, you only return json object and there will be no access to these objects.
For you to have access to these objects what you need to do is connect once more, in react itself, with the same firebase and that's how you enjoy all the worlds that firebase has to offer.
When you log in again, the user does not need to know about it, since when you log in you will reset the password, and choose a random password, it will solve all your problems.
I think this is the most likely solution, but it is not for production
Please update me.
Is there a reason why you're not authenticating directly from the client? The thing is you have to pass in some way the authenticated state from the server to the front...
You have signed in with firebase on your server but you did not sign in with firebase on the front end. Or maybe you did in setAuthorizationHeader(res.data.token); but I'd be curious to know how you did that. It would have been interesting to be able to authenticate with nodejs and then send the tokenId which has been generated, that is data.user.getIdToken(), to the client which the client would then pass to firebase.auth().signInWithToken(token) but this is not possible. If you want to know more about it, I invite you to read this issue (a feature request).
The way to solve this problem is to use Admin SDK and create a custom token.
Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken() method.
To achieve this, you must create a server endpoint that accepts sign-in credentials—such as a username and password—and, if the credentials are valid, returns a custom JWT. The custom JWT returned from your server can then be used by a client device to authenticate with Firebase (iOS, Android, web). Once authenticated, this identity will be used when accessing other Firebase services, such as the Firebase Realtime Database and Cloud Storage. Furthermore, the contents of the JWT will be available in the auth object in your Realtime Database Rules and the request.auth object in your Cloud Storage Security Rules.
Here are the steps:
First, you will add the SDK to your server:
yarn add firebase-admin --save
and import it
const admin = require("firebase-admin")
Go over to your Project settings under the "Service accounts" tab.
and click on "Generate a new private key"
a file has been downloaded and saved on your machine. From there, you will either import the file and initialize admin like this:
var serviceAccount = require("/path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
or better yet, in the console
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/serviceAccountKey.json"
and in your file
const credential = admin.credential.applicationDefault() // this will automatically find your env variable
admin.initializeApp({
credential
})
Note: don't forget to set the proper permissions to the private key file with chmod (I had to).
nodejs
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
admin
.auth()
.createCustomToken(data.user.uid)
.then((customToken) => {
console.log('customToken', customToken)
// send token back to client here
res.send(customToken)
})
.catch((error) => {
console.log('Error creating custom token:', error);
});
})
.catch((err) => {
console.error(err);
});
and then on the client:
// get the token and then
firebase.auth().signInWithCustomToken(token)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
});
Another solution would be not using firebase on the client at all and use the backend as some sort of proxy between firebase and the client. The client would make a request to the backend which in turn would interrogate firebase.
in my case, faced same problem with rule's.
please give a try, change your rue and check whether its working or not
I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
src/App.vue
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
public/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
src/plugins/firebase.js
import firebase from '#firebase/app'
import '#firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
What did I do wrong?
I've found a solution in another QA here in StackOverflow (which I can't find anymore for some reason).
Turns out you have to use Firebase API v7.8.0 instead of 5.5.6 like the docs said at the time. So those first two lines in public/firebase-messaging-sw.js should read like this instead:
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js')
Same issue i was faced. In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different. After set same version in "firebase-messaging-sw.js" importScripts which was in
"package.json", my issue is resolved.
Before change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
After change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
In my case the version on package.json (8.2.1) was different from the actual SDK_VERSION (8.0.1)
After changed service-workers with the same version worked..
I had a bunch of issues setting firebase push notifications for Vue 3 (with Vite), and I had PWA support enabled with vite-plugin-pwa, so it felt like I was flying blind half the time. I was finally able to set up support for PWA, but then I ran into the following issues:
I was getting notifications in the background (when my app was not in focus), but not in the foreground.
When I did get notifications in the background, it appeared twice.
Here's my complete setup. I have the latest firebase as of this post (9.12.1)
// firebase-messaging-sw.js file in the public folder
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-app-compat.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-messaging-compat.js"
);
// Initialize Firebase
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "/icon.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I've seen some posts online provide the onBackgroundMessage here in the service worker, but I experimented with commenting it out and it seemed to fix the issue of notifications appearing twice.
Next, is a firebase.js file with which I retrieve tokens and subsequently listen for foreground notifications.
// firebase.js in same location with main.js
import firebase from "firebase/compat/app";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = firebase.initializeApp(firebaseConfig);
export default getMessaging(app);
And then in main.js
import App from "./App.vue";
import firebaseMessaging from "./firebase";
const app = createApp(App)
app.config.globalProperties.$messaging = firebaseMessaging; //register as a global property
And finally, in App.vue (or wherever you wish to get tokens and send to your serverside)...
import {getToken, onMessage} from "firebase/messaging";
export default {
mounted() {
getToken(this.$messaging, {
vapidKey:
"XXX-XXX",
})
.then((currentToken) => {
if (currentToken) {
console.log("client token", currentToken);
onMessage(this.$messaging, (payload) => {
console.log("Message received. ", payload);
});
//send token to server-side
} else {
console.log(
"No registration token available. Request permission to generate one"
);
}
})
.catch((err) => {
console.log("An error occurred while retrieving token.", err);
});
}
}
Of course don't forget the vapidKey. Took a minute, but it worked perfectly.
For now, I am not offering any opinion as to what the foreground notification should look like, so I am merely logging the payload. But feel free to show it however you deem fit.
I'm trying to add authentication using Firebase in my Vue app, but I'm getting [Vue warn]: Error in v-on handler: "TypeError: _config_firebase__WEBPACK_IMPORTED_MODULE_8__.user.SignInWithEmailAndPassword is not a function" error.
Here is my irebase config file:
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_AUTH_DOMAIN",
databaseURL: "MY_DB_URL",
projectId: "MY_PROJECT_ID",
storageBucket: "MY_STORAGE_BUCKET",
messagingSenderId: "MY_MESSAGE_SENDER_ID",
appId: "MY_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a Firestore instance
export const user = firebase.auth();
export const db = firebase.firestore();
Then the action in Vuex:
import { db, user } from "./config/firebase";
loginUser({ commit }, payload) {
user
.SignInWithEmailAndPassword(payload)
.then(user => {
console.log(user);
commit("SET_USER", user);
})
.catch(error => {
commit("setLoading", false);
commit("setError", error);
console.log(error);
});
router.push("/");
}
So far, I have been able to Create, Read, Update and Delete, although, the config file was slightly different than this, when I added auth was when I altered the code.
Change this:
user.SignInWithEmailAndPassword(payload)
into this:
user.signInWithEmailAndPassword(payload)
From the docs:
Asynchronously signs in using an email and password.
I am trying to authenticate a user and also organize the users in my database by their uid and then have the data field be by email. The users are successfully being authenticated however nothing appears in my firestore database.
My firestore security rules are in test mode so there should be no issue with permissions. In my action dispatch, I am successfully getting the user from firebase with their uid, access token, and everything else. I believe the error must be some way I am trying to connect to the firestore.
In my app.js file I initialize firebase like this-
import firebase from 'firebase';
import '#firebase/firestore';
componentDidMount() {
const firebaseConfig = {
apiKey: 'xxxxxxxx',
authDomain: 'xxxxxxxxx.firebaseapp.com',
databaseURL: 'xxxxxxxx.firebaseio.com',
projectId: 'xxxxxxxx',
storageBucket: 'xxxxxxx.appspot.com',
messagingSenderId: 'xxxxxxxxxxx',
appId: 'xxxxxxxxxxxxxxxxxxxx'
};
firebase.initializeApp(firebaseConfig);
}
Then this is how I am trying to make the call to put the user into the database-
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((user) =>
dispatch({ type: USER_LOGIN_SUCCESS, payload: user });
const dbRoot = firebase.firestore();
dbRoot.collection('users').doc(user.user.uid).set({ email });
});
Also at the top of that file, I am importing as follows
import firebase from 'firebase';
import '#firebase/firestore';
Again, these users are being successfully authenticated but they are not appearing in the firestore database.
You have to add a collection to the database and add data.
const dbRoot = firebase.firestore().collection('users');
...
addData() {
dbRoot.add({
user: user.user.uid,
email : email,
complete: true,
});
OR
const dbRoot = firebase.firestore().collection('users');
...
const defaultDoc = {
email: email
};
async addData() {
await dbRoot.doc(user.user.uid).set(defaultDoc);
}