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

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

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:


{
  &quot;rules&quot;: {
     &quot;.read&quot;: &quot;true&quot;,
     &quot;.write&quot;: &quot;auth != null&quot;
  }
}

This is part of my app.module.ts:

import firebase from &#39;firebase/compat/app&#39;;

import { environment } from &#39;../environments/environment&#39;;
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&lt;any&gt; {
    const email = &#39;mail@gmail.com&#39;;
    const password = &#39;pass&#39;;
  
    // Authenticate the user
    return from(firebase.auth().signInWithEmailAndPassword(email, password)).pipe(
      switchMap((userCredential: any) =&gt; {
        // User is now authenticated
        console.log(&#39;Authentication successful&#39;);
        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) =&gt; {
            // Create headers and add the access token
            const headers = new HttpHeaders({
              &#39;Content-Type&#39;: &#39;application/json&#39;,
              Authorization: `Bearer ${accessToken}`
            });
    
            console.log(headers); // Log headers to verify its value
    
            // Make the HTTP request with the headers
            return this.httpClient.get(&#39;&lt;URL&gt;/ip.json&#39;, { headers });
          })
        );
      })
    );
  }

And then NgOnInit:

    const data = { name: &#39;John Doe&#39;, age: 25 };

    this.writeDataToDatabase(data).subscribe(
      response =&gt; {
        console.log(&#39;Data written successfully:&#39;, response);
      },
      error =&gt; {
        console.error(&#39;Error writing data:&#39;, 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=&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:

确定