首页 > 解决方案 > Firebase 存储安全规则 400 错误问题“权限被拒绝。无法访问存储桶...”(在部署时,在本地主机上工作时)

问题描述

我在我的应用程序中获得了上传文件功能,这在localhost. 但是,何时运行firebase deploy并部署应用程序我收到以下错误,缺少权限。

编辑:我可以部署,CLI 没有问题,只是在部署时它不能像在localhost.

试过:

HTML 代码

<mat-form-field>
        <!-- Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side. -->
        <ngx-mat-file-input
          [accept]="[
            '.doc',
            '.docx',
            '.jpg',
            '.jpeg',
            '.pdf',
            '.png',
            '.xls',
            '.xlsx'
          ]"
          (change)="uploadFile($event)"
          formControlName="fileUploader"
          multiple
          aria-label="Here you can add additional files about your project, which can be helpeful for us."
          placeholder="Additional files"
          title="Additional files"
          type="file"
        >
        </ngx-mat-file-input>
        <mat-icon matSuffix>folder</mat-icon>
        <mat-hint
          >Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
          maximum files upload size: 20 MB.
        </mat-hint>
        <mat-error
          *ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
        >
          This size is too large,
          <strong
            >maximum acceptable upload size is
            {{
              contactForm.get('fileUploader')?.getError('maxContentSize')
                .maxSize | byteFormat
            }}</strong
          >
          (uploaded size:
          {{
            contactForm.get('fileUploader')?.getError('maxContentSize')
              .actualSize | byteFormat
          }}).
        </mat-error>
      </mat-form-field>

TypeScript(在 Angular 中)代码

/**
   * @description Upload additional files to Cloud Firestore and get URL to the files.
   * @param {event} - object of sent files.
   * @returns {void}
   */
  public uploadFile(event: any): void {
    // Iterate through all uploaded files.
    for (let i = 0; i < event.target.files.length; i++) {
      const randomId = Math.random()
        .toString(36)
        .substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.

      const file = event.target.files[i]; // Get each uploaded file.

      // Get file reference.
      const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
        randomId
      );

      // Create upload task.
      const task: AngularFireUploadTask = this.angularFireStorage.upload(
        randomId,
        file
      );

      // Upload file to Cloud Firestore.
      task
        .snapshotChanges()
        .pipe(
          finalize(() => {
            fileRef.getDownloadURL().subscribe(downloadURL => {
              this.angularFirestore
                .collection('files')
                .add({ downloadURL: downloadURL });
              this.downloadURL.push(downloadURL);
            });
          }),
          catchError((error: any) => {
            return throwError(error);
          })
        )
        .subscribe();
    }
  }

存储规则

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
        allow read; // Required in order to send this as attachment.
      // Allow write files Firebase Storage, only if:
      // 1) File is no more than 20MB
      // 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
      allow write: if request.resource.size <= 20 * 1024 * 1024
                   && (request.resource.contentType.matches('application/msword')
                   || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                   || request.resource.contentType.matches('image/jpg')
                   || request.resource.contentType.matches('image/jpeg')
                   || request.resource.contentType.matches('application/pdf')
                                     || request.resource.contentType.matches('image/png')
                   || request.resource.contentType.matches('application/vnd.ms-excel')
                   || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
    }
  }
}

标签: angularfirebasegoogle-cloud-storagefirebase-storagefirebase-security

解决方案


由于您收到的消息,您的问题与Firebase 中的 IAM 角色有关。

这里是这些的快速概述

检查您收到的错误消息,并确保您正在部署的实例或您正在使用的服务帐户具有允许他们执行您想要执行的操作的所需角色。


推荐阅读