Issue
I updated my write rules for Firebase Realtime database and I am trying to modify my POST requests to first be authenticated. No matter what I try I always get 401 (Unauthorized) error in my console.
These are my rules:
{
"rules": {
".read": "true",
".write": "auth != null"
}
}
This is part of my app.module.ts:
import firebase from 'firebase/compat/app';
import { environment } from '../environments/environment';
firebase.initializeApp(environment.firebase)
Environment was copied from web app that I created in Firebase.
And this is my code for posting in my component:
writeDataToDatabase(data: any): Observable<any> {
const email = 'mail@gmail.com';
const password = 'pass';
// Authenticate the user
return from(firebase.auth().signInWithEmailAndPassword(email, password)).pipe(
switchMap((userCredential: any) => {
// User is now authenticated
console.log('Authentication successful');
console.log(userCredential); // Log userCredential to verify its value
// Get the access token from the user credential
return from(userCredential.user.getIdToken()).pipe(
switchMap((accessToken) => {
// Create headers and add the access token
const headers = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`
});
console.log(headers); // Log headers to verify its value
// Make the HTTP request with the headers
return this.httpClient.get('<URL>/ip.json', { headers });
})
);
})
);
}
And then NgOnInit:
const data = { name: 'John Doe', age: 25 };
this.writeDataToDatabase(data).subscribe(
response => {
console.log('Data written successfully:', response);
},
error => {
console.error('Error writing data:', error);
}
);
It throws me 401 Unauthorized error. User with the credentials is added to the Authorization in Firebase Console (when I give wrong credentials it throws me an error regarding the credentials so I am 100% sure they are good)
Does anyone know what is wrong here? I would really appreciate help.
Solution
From the Firebase documentation authenticating REST API calls with an ID token:
To send authenticated requests to the Realtime Database REST API, pass the ID token generated above as the
auth=<ID_TOKEN>
query string parameter. Here is an examplecurl
request to read Ada's name:curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>"
So you'll see that you need to pass the ID token as a parameter to the request, not in an Authorization header.
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.