Not getting token in firebase - javascript

I am using fire base for push notification in react-native.
For getting token I am using this code
const fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
this.sendFcmToken(fcmToken);
// user has a device token
}
But I am not getting token even if user have permission for token access.
I am using firebase 5.1.1
"react-native-firebase": "^5.1.1"
I don't want to upgrade version, so what I can do?
I think problem is with getToken() method as its deprecated so please suggest an alternative for it.

Related

Firebase admin getUser invalid grant

Verifying id token works without a problem, but strangely enough when I use firebaseAdmin.auth().getUser(uid) I get the following error:
FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: invalid_grant (Invalid grant: account not found)". There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.
at C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\firebase-admin\lib\app\firebase-app.js:85:19
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async getServerSideProps (webpack-internal:///./pages/user/[uid].tsx:30:30)
at async Object.renderToHTML (C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\render.js:506:20)
at async doRender (C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\base-server.js:708:34)
at async cacheEntry.responseCache.get.isManualRevalidate.isManualRevalidate (C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\base-server.js:813:28)
at async C:\Users\dinop\Documents\VS Code\Personal\next_social_app\node_modules\next\dist\server\response-cache\index.js:80:36 {
errorInfo: {
code: 'app/invalid-credential',
message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: invalid_grant (Invalid grant: account not found)". There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.'
},
codePrefix: 'app'
}
Just to clarify, this is a simple code snippet used in getServerSideProps:
const token = await firebaseAdmin.auth().verifyIdToken(cookies.token);
const pageUid: any = ctx.params?.uid;
console.log(pageUid); // gets printed, verifying id token works as explained.
const pageUserData = await firebaseAdmin.auth().getUser(pageUid); // throws the error
PageUid in this case exists just to be clear. I suspect it's a permission issue. The service account in use has the following permissions:
Firebase Admin SDK Administrator Service Agent
Firebase App Check Admin
Firebase Realtime Database Admin
Service Account Token Creator
Storage Admin
I generated a new Admin SDK key (even though I already had one), this solved the issue.

Cannot access Firebase Storage with or without authentication (web)

I want to use Firebase Storage (web version 9.6.0) but the access to Firebase Storage is being denied with the following error:
unhandledRejection: FirebaseError: Firebase Storage: User is not authenticated, please authenticate using Firebase Authentication and try again. (storage/unauthenticated)
You would want to say to me that I just need the user to be authenticated, but two problems:
the user is already authenticated (getAuth().currentUser returns something)
the rules in Firebase Storage don't say that a user needs to be authenticated:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
}
}
The problem is caused when I try this:
// initializeApp(config) etc.
const storage = getStorage() // enabled in Firebase console
const a_correct_path = "something..."
const reference = ref(storage, a_correct_path) // this is working (I get the right reference)
const url = getDownloadURL(reference) // this throws the error
NOTE: Because I have already had problems with it, please not that I'm using App Check which I have enforced for the Storage feature.
Why did I do wrong?
Firstly,
The
const a_correct_path = ""
Can't be empty and should have the correct path if it's in a folder.
But if that doesn't help... Reset your storage rules to the first one.
If that doesn't work, check the line where you imported things from firebase
On the Firebase Console, go to Authentication. Check that the user that you are logged in with appears there. If the user is not there then that means you are not authenticating users with Firebase Authentication, and maybe you're just adding users to your Firestore. That is why the error is placing emphasis on Firebase Authentication.
User is not authenticated, please authenticate using Firebase Authentication and try again.

SecureStore deletes my token each time I refresh the expo client

I have problem retrieving my authentication token from SecureStore while I develop my app in the expo client.
I’m trying to implement this authentication flow from react navigation using secureStore instead of Async storage: https://reactnavigation.org/docs/en/4.x/auth-flow.html
Currently, when I login my token is stored in SecureStore. I know this because I can then use it for authorising my requests.
My problem is when the expo client I'm developing my app in refreshes, the token seems to disappear so I have to sign in again.
Does the expo client app refreshing clear the token from secure store or is there a bug in my code that stops me from retrieving the token when I am opening my app again:
useEffect(() => {
_bootstrapAsync = async () => {
const token = await SecureStore.getItemAsync('token')
navigation.navigate(token ? 'App' : 'Auth');
};
_bootstrapAsync();
}, [])
I have a hunch what it could be.
Is the token stored correctly?
And won't the token be overwritten when reloading?
I don't know which module you use for saving but I recommend "expo-secure-store".
In my applications when I reload everything works.
Try wrapping a try-catch block around both getItemAsync and setItemAsync and see whether you're getting any errors as a start.
There's also a chance that you're using an old import syntax, make sure you're using import * as SecureStore from "expo-secure-store", this will cause an error like undefined is not an object so the data was never saved.
Solved this by adding a useEffect that would check if there is a Token, if there was a token i set it and if not i removed it.

Firebase authentication error: auth/invalid-credential

I've been experimenting with the authentication service provided by firebase for more than 2 weeks. Everything was perfectly working until yesterday it became impossible for me to use the facebook auth provider neither twitter to make users connect to my web app.
I've tried to sign out and sign in, I deleted my facebook and twitter apps and created others even with other accounts and the problem persists.
The same problem occurred when I tried to use the code they provide on their github which was working before.
The strange thing is that it's working fine when I use the google provider or the sign in with email and password method.
PS: I made sure the providers are enabled in the console.
const signInWithFacebookButton = document.getElementById('signInWithFacebook');
const auth = firebase.auth();
const signInWithFacebook = () => {
const facebookProvider = new firebase.auth.FacebookAuthProvider();
auth.signInWithPopup(facebookProvider)
.then(() => {
console.log('Successfully signed in');
})
.catch(error => {
console.error(error);
})
}
signInWithFacebookButton.addEventListener('click', signInWithFacebook);
Error message when I try to authenticate using facebook :
{code: "auth/invalid-credential", message: "The supplied auth credential is malformed or has expired."}
Error message when I try to authenticate using twitter:
{code: "auth/invalid-credential", message: "Error getting request token: 403 <?xml version="1.…ode-project-fd88e.firebaseapp.com/__/auth/handler"}
For Twitter login, the error code 403 indicates that access to the URL by the client is Forbidden. It gives such an error because you have to whitelist callback URLs(your site).
From documentation,
As part of our continued effort to ensure safety and security on the Twitter developer platform, any developer using Sign in with Twitter must explicitly declare their callback URLs in a whitelist in the Twitter apps settings which can be accessed in the apps dashboard when logged into your Twitter account on developer.twitter.com. This means that if the callback_url parameter used with the oauth/request_token endpoint isn't whitelisted, you will receive an error.
So in Twitter app settings, you have to add your URL say for example,
https://sitename.example.com/auth/twitter and https://sitename.example.com/auth/twitter/callback
You want to use https://yourdomain.com?source=twitter as your callback URL
Add this to the Twitter app dashboard: https://yourdomain.com
Use this in your call to oauth/request_token: https://yourdomain.com?source=twitter.
Refer this community article for more detail:-
Twitter callback URLs
This is worth as an answer: Always click to show your Facebook app secret before copying and pasting it into Firebase setting console. It is counter-intuitive, but Facebook did not implement the clipboard correctly so the hidden asterisk characters will just be copied and pasted verbatim.

Error when authenticating with Firebase OauthToken method

I am trying to authenticate a user in my ionic app using the authWithOAuthToken() method in Firebase. I am getting this error -> {"code":"INVALID_CREDENTIALS","details":"{\"providerErrorInfo\":{}}"} with my firebase ref, when I try with another firebase ref, it works.
In Firebase Error Listing, INVALID CREDENTIALS means
The specified authentication credentials are invalid. This may occur when credentials are malformed or expired.
But I am not passing any credential to the method
var Ref = new Firebase('https://<firebase-ref>.firebaseio.com');
Ref.authWithOAuthToken('facebook', '<facebook token>', function(error, authData) {
if (error) {
console.log('Login Failed!', JSON.stringify(error));
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
Anybody encountered this before?
Go to Facebook Tab inside Login & Auth in firebase project, Copy and paste Credentials from your facebook developer app and try running your app, if you have already entered your details, make sure they are correct , if it still doesn't work check by creating a new facebook developer app and again enter the details in firebase

Categories