401 未经授权的错误 Firebase 使用 Angular

huangapple go评论105阅读模式
英文:

401 Unauthorized error Firebase using Angular

问题

这是我的 Firebase 实时数据库写规则的更新,我尝试修改我的 POST 请求以进行身份验证。无论我尝试什么,控制台始终显示 401(未经授权)错误。

这是我的规则:

  1. {
  2. "rules": {
  3. ".read": "true",
  4. ".write": "auth != null"
  5. }
  6. }

这是我的 app.module.ts 的一部分:

  1. import firebase from 'firebase/compat/app';
  2. import { environment } from '../environments/environment';
  3. firebase.initializeApp(environment.firebase)

环境变量是从我在 Firebase 中创建的 Web 应用中复制过来的。

这是我在组件中进行 POST 请求的代码:

  1. writeDataToDatabase(data: any): Observable<any> {
  2. const email = 'mail@gmail.com';
  3. const password = 'pass';
  4. // 验证用户
  5. return from(firebase.auth().signInWithEmailAndPassword(email, password)).pipe(
  6. switchMap((userCredential: any) => {
  7. // 用户现在已经通过身份验证
  8. console.log('验证成功');
  9. console.log(userCredential); // 记录 userCredential 以验证其值
  10. // 从用户凭证中获取访问令牌
  11. return from(userCredential.user.getIdToken()).pipe(
  12. switchMap((accessToken) => {
  13. // 创建标头并添加访问令牌
  14. const headers = new HttpHeaders({
  15. 'Content-Type': 'application/json',
  16. Authorization: `Bearer ${accessToken}`
  17. });
  18. console.log(headers); // 记录标头以验证其值
  19. // 使用标头进行 HTTP 请求
  20. return this.httpClient.get('<URL>/ip.json', { headers });
  21. })
  22. );
  23. })
  24. );
  25. }

然后在 NgOnInit 中:

  1. const data = { name: 'John Doe', age: 25 };
  2. this.writeDataToDatabase(data).subscribe(
  3. response => {
  4. console.log('数据写入成功:', response);
  5. },
  6. error => {
  7. console.error('写入数据时出错:', error);
  8. }
  9. );

它会抛出 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:

  1. {
  2. &quot;rules&quot;: {
  3. &quot;.read&quot;: &quot;true&quot;,
  4. &quot;.write&quot;: &quot;auth != null&quot;
  5. }
  6. }

This is part of my app.module.ts:

  1. import firebase from &#39;firebase/compat/app&#39;;
  2. import { environment } from &#39;../environments/environment&#39;;
  3. 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:

  1. writeDataToDatabase(data: any): Observable&lt;any&gt; {
  2. const email = &#39;mail@gmail.com&#39;;
  3. const password = &#39;pass&#39;;
  4. // Authenticate the user
  5. return from(firebase.auth().signInWithEmailAndPassword(email, password)).pipe(
  6. switchMap((userCredential: any) =&gt; {
  7. // User is now authenticated
  8. console.log(&#39;Authentication successful&#39;);
  9. console.log(userCredential); // Log userCredential to verify its value
  10. // Get the access token from the user credential
  11. return from(userCredential.user.getIdToken()).pipe(
  12. switchMap((accessToken) =&gt; {
  13. // Create headers and add the access token
  14. const headers = new HttpHeaders({
  15. &#39;Content-Type&#39;: &#39;application/json&#39;,
  16. Authorization: `Bearer ${accessToken}`
  17. });
  18. console.log(headers); // Log headers to verify its value
  19. // Make the HTTP request with the headers
  20. return this.httpClient.get(&#39;&lt;URL&gt;/ip.json&#39;, { headers });
  21. })
  22. );
  23. })
  24. );
  25. }

And then NgOnInit:

  1. const data = { name: &#39;John Doe&#39;, age: 25 };
  2. this.writeDataToDatabase(data).subscribe(
  3. response =&gt; {
  4. console.log(&#39;Data written successfully:&#39;, response);
  5. },
  6. error =&gt; {
  7. console.error(&#39;Error writing data:&#39;, error);
  8. }
  9. );

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=&lt;ID_TOKEN&gt; 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.

huangapple
  • 本文由 发表于 2023年6月22日 19:29:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定