简体   繁体   English

如何在不使用 firebase 身份验证的情况下保护 firebase 存储? (下一个)

[英]How to secure firebase storage without using firebase auth? (nextjs)

Im using firebase storage for uploading files within my next.js page.我使用 firebase 存储在我的next.js页面中上传文件。 Clients fill in a form and the files are going to be uploaded in firebase storage.客户填写表格,文件将上传到 firebase 存储中。 (Im using a different database) (我使用不同的数据库)

I'm wondering how I can only allow uploading files within this post request.我想知道如何只允许在此发布请求中上传文件。

import React, { useState } from "react";
import { render } from "react-dom";
import { storage } from "../src/firebase/index";

const ReactFirebaseFileUpload = () => {
  const [image, setImage] = useState(null);
  const [url, setUrl] = useState("");
  const [progress, setProgress] = useState(0);

  const handleChange = e => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
    }
  };

  const handleUpload = () => {
    const uploadTask = storage.ref(`images/${image.name}`).put(image);
    uploadTask.on(
      "state_changed",
      snapshot => {
        const progress = Math.round(
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        );
        setProgress(progress);
      },
      error => {
        console.log(error);
      },
      () => {
        storage
          .ref("images")
          .child(image.name)
          .getDownloadURL()
          .then(url => {
            setUrl(url);
          });
      }
    );
  };

  return (
    <div>
      <progress value={progress} max="100" />
      <br />
      <br />
      <input type="file" onChange={handleChange} />
      <button onClick={handleUpload}>Upload</button>
      <br />
      {url}
      <br />
      <img src={url || "http://via.placeholder.com/300"} alt="firebase-image" />
    </div>
  );

}

export default ReactFirebaseFileUpload;

This is my working example with open rules.这是我使用开放规则的工作示例。

My rules:我的规则:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if true;
    }
  }
}

I want to put the upload on the next.js api route system, so we have an api to call.我想把上传放在 next.js api 路由系统上,所以我们有一个 api 可以调用。 In my imagination either I can somehow secure this part then with headers or something OR maybe even better define something in my storage rules.在我的想象中,我可以以某种方式保护这部分,然后使用标题或其他东西,或者甚至更好地在我的存储规则中定义一些东西。

i really didn't find anything smart to define there.我真的没有找到任何明智的定义。

Please help me guide threw this.请帮我指导扔这个。

If anyone (without Auth) needs to upload data you need to give him write access to a specific path in your storage.如果任何人(没有 Auth)需要上传数据,您需要授予他对您存储中特定pathwrite权限。

To get the donwloadURL from that ref it needs the read rights.要从该ref获取donwloadURL ,它需要read权限。

If it is possible from your bussines logic that anyone can upload but desn't need the downloadURL you could remove the read for everyone.如果您的业务逻辑有可能任何人都可以上传但不需要downloadURL ,您可以删除所有人的read

I would deffinitely recommend to upload such files under a specific path like "public" and at least make restrictions like file size and contentType like here for images:我肯定会建议在特定path下上传此类文件,例如“公共”,并至少对图像进行文件大小和内容类型等限制:

match /public/{allPaths=**} {
        allow read: if true
        allow write: if request.resource.size < 15 * 1024 * 1024
                    && request.resource.contentType.matches('image/.*') 
    }

Don't forget that the downloadURL is a public access URL for every file.不要忘记, downloadURL是每个文件的公共访问 URL。 So anone who has that URL can acess that file.因此,拥有该 URL 的人可以访问该文件。 You need the read rules to get that downloadURL from a reference but if you got the downloadURL from somewhere else you could still access the file.您需要read规则才能从参考中获取该downloadURL ,但如果您从其他地方获取downloadURL ,您仍然可以访问该文件。 They are made in a way that could not ques them very easy so it's is quite safe approach.它们的制作方式不容易质疑它们,因此这是一种非常安全的方法。

You could use the admin SDK to do it on your own if you can and just return the downloadURL or use Firebase Cloud Functions with storage triggers to listen for file uploads (with restricted access like above) and store the downloadURL somewhere you need it.如果可以的话,您可以使用管理员 SDK 自行完成,只需返回downloadURL或使用带有存储触发器的 Firebase Cloud Functions 来侦听文件上传(具有上述访问权限)并将downloadURL存储在您需要的地方。

Here you have a very good explanation how all that can work together. 在这里,您可以很好地解释所有这些如何协同工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase.auth().currentuser 不在 nextjs 上工作 - Firebase.auth().currentuser not working on nextjs NodeJs 和 React 与 Firebase 身份验证:如何保护 nodejs api 端点? - NodeJs and React with Firebase auth: how to secure nodejs api endpoints? 使用 Firebase 身份验证和 gAPI? - Using Firebase Auth & gAPI? 如何使用firebase的GUI从firebase存储中获取图像? - How to get an image from firebase storage using the GUI of firebase? 如何在类中导入 Firebase Auth、Firestore 和 Firebase Storage 节点包以及它们的 TypeScript 类型? - How do you import Firebase Auth, Firestore and Firebase Storage node packages as well as their TypeScript's types in a class? 如何在不导致内存泄漏的情况下添加身份验证侦听器火力基地 - How to add an auth listener firebase without getting memory leak 如何在 firebase.storage() 请求中添加身份验证或参数以响应受限存储规则 - How to add auth or params in firebase.storage() request from react with restricted storage rules 使用Nextjs的getInitialProps为Firebase DB设置状态 - Set State Using getInitialProps of Nextjs for firebase DB 使用firebase,nextjs将对象添加到嵌套数组 - Adding object to nested array using firebase, nextjs 在 NextJS 中使用 firestore 时发生 Firebase 错误 - Firebase error while using firestore in NextJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM