英文:
401 Unauthorized error Firebase using Angular
问题
这是我的 Firebase 实时数据库写规则的更新,我尝试修改我的 POST 请求以进行身份验证。无论我尝试什么,控制台始终显示 401(未经授权)错误。
这是我的规则:
{
"rules": {
".read": "true",
".write": "auth != null"
}
}
这是我的 app.module.ts 的一部分:
import firebase from 'firebase/compat/app';
import { environment } from '../environments/environment';
firebase.initializeApp(environment.firebase)
环境变量是从我在 Firebase 中创建的 Web 应用中复制过来的。
这是我在组件中进行 POST 请求的代码:
writeDataToDatabase(data: any): Observable<any> {
const email = 'mail@gmail.com';
const password = 'pass';
// 验证用户
return from(firebase.auth().signInWithEmailAndPassword(email, password)).pipe(
switchMap((userCredential: any) => {
// 用户现在已经通过身份验证
console.log('验证成功');
console.log(userCredential); // 记录 userCredential 以验证其值
// 从用户凭证中获取访问令牌
return from(userCredential.user.getIdToken()).pipe(
switchMap((accessToken) => {
// 创建标头并添加访问令牌
const headers = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`
});
console.log(headers); // 记录标头以验证其值
// 使用标头进行 HTTP 请求
return this.httpClient.get('<URL>/ip.json', { headers });
})
);
})
);
}
然后在 NgOnInit 中:
const data = { name: 'John Doe', age: 25 };
this.writeDataToDatabase(data).subscribe(
response => {
console.log('数据写入成功:', response);
},
error => {
console.error('写入数据时出错:', error);
}
);
它会抛出 401 未经授权错误。具有凭证的用户已添加到 Firebase 控制台的授权部分(当我提供错误的凭证时,它会抛出与凭证相关的错误,所以我可以百分之百确定它们是正确的)。
有人知道这里出了什么问题吗?我真的很感激帮助。
英文:
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.
答案1
得分: 0
根据 Firebase 文档 使用 ID 令牌进行 REST API 调用身份验证:
> 要向实时数据库 REST API 发送经过身份验证的请求,请将上面生成的 ID 令牌作为 auth=<ID_TOKEN>
查询字符串参数传递。以下是一个用于读取 Ada 的名称的示例 curl
请求:
>
> curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>"
所以你会看到你需要将 ID 令牌作为参数传递给请求,而不是放在授权头部。
英文:
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 example curl
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论