下载文件时如何传递身份验证令牌?

问题描述 投票:2回答:2

我有一个Web应用程序,其中Angular(7)前端与服务器上的REST API进行通信,并使用OpenId Connect(OIDC)进行身份验证。我正在使用HttpInterceptor为我的HTTP请求添加Authorization标头,以向服务器提供身份验证令牌。到现在为止还挺好。

但是,除了传统的JSON数据外,我的后端还负责即时生成文档。在我添加身份验证之前,我可以直接链接到这些文档,如:

<a href="https://my-server.com/my-api/document?id=3">Download</a>

但是,现在我已经添加了身份验证,这不再有效,因为浏览器在获取文档时不在请求中包含auth令牌 - 所以我从服务器获得了401-Unathorized响应。

所以,我不能再依赖于一个vanilla HTML链接 - 我需要创建自己的HTTP请求,并明确添加auth令牌。但是,如何确保用户体验与用户点击链接相同?理想情况下,我希望使用服务器建议的文件名保存文件,而不是通用文件名。

angular http-headers oidc auth-token
2个回答
1
投票

我把一些“在我的机器上工作”的东西拼凑在一起,部分基于this answer和其他类似的东西 - 虽然我的努力是通过打包作为一个可重复使用的指令“Angular-ized”。它没有太大的意义(大多数代码正在进行笨拙的工作,根据服务器发送的content-disposition头来确定文件名应该是什么)。

下载file.directive.ts:

import { Directive, HostListener, Input } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Directive({
  selector: '[downloadFile]'
})
export class DownloadFileDirective {
  constructor(private readonly httpClient: HttpClient) {}

  private downloadUrl: string;

  @Input('downloadFile')
  public set url(url: string) {
    this.downloadUrl = url;
  };

  @HostListener('click')
  public async onClick(): Promise<void> {

    // Download the document as a blob
    const response = await this.httpClient.get(
      this.downloadUrl,
      { responseType: 'blob', observe: 'response' }
    ).toPromise();

    // Create a URL for the blob
    const url = URL.createObjectURL(response.body);

    // Create an anchor element to "point" to it
    const anchor = document.createElement('a');
    anchor.href = url;

    // Get the suggested filename for the file from the response headers
    anchor.download = this.getFilenameFromHeaders(response.headers) || 'file';

    // Simulate a click on our anchor element
    anchor.click();

    // Discard the object data
    URL.revokeObjectURL(url);
  }

  private getFilenameFromHeaders(headers: HttpHeaders) {
    // The content-disposition header should include a suggested filename for the file
    const contentDisposition = headers.get('Content-Disposition');
    if (!contentDisposition) {
      return null;
    }

    /* StackOverflow is full of RegEx-es for parsing the content-disposition header,
    * but that's overkill for my purposes, since I have a known back-end with
    * predictable behaviour. I can afford to assume that the content-disposition
    * header looks like the example in the docs
    * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
    *
    * In other words, it'll be something like this:
    *    Content-Disposition: attachment; filename="filename.ext"
    *
    * I probably should allow for single and double quotes (or no quotes) around
    * the filename. I don't need to worry about character-encoding since all of
    * the filenames I generate on the server side should be vanilla ASCII.
    */

    const leadIn = 'filename=';
    const start = contentDisposition.search(leadIn);
    if (start < 0) {
      return null;
    }

    // Get the 'value' after the filename= part (which may be enclosed in quotes)
    const value = contentDisposition.substring(start + leadIn.length).trim();
    if (value.length === 0) {
      return null;
    }

    // If it's not quoted, we can return the whole thing
    const firstCharacter = value[0];
    if (firstCharacter !== '\"' && firstCharacter !== '\'') {
      return value;
    }

    // If it's quoted, it must have a matching end-quote
    if (value.length < 2) {
      return null;
    }

    // The end-quote must match the opening quote
    const lastCharacter = value[value.length - 1];
    if (lastCharacter !== firstCharacter) {
      return null;
    }

    // Return the content of the quotes
    return value.substring(1, value.length - 1);
  }
}

使用方法如下:

<a downloadFile="https://my-server.com/my-api/document?id=3">Download</a>

......或者,当然:

<a [downloadFile]="myUrlProperty">Download</a>

请注意,我没有在此代码中明确地将auth令牌添加到HTTP请求中,因为我的HttpClient实现已经处理了所有HttpInterceptor调用(未显示)。要在没有拦截器的情况下执行此操作,只需在请求中添加标头(在我的示例中为Authorization标头)。

另外值得一提的是,如果被调用的Web API位于使用CORS的服务器上,则可能会阻止客户端代码访问内容处置响应头。要允许访问此标头,您可以让服务器发送适当的access-control-allow-headers标头。


0
投票

Angular(7)前端与服务器上的REST API进行通信

然后:

<a href="https://my-server.com/my-api/document?id=3">Download</a>

这告诉我你的RESTful API并不是真正的RESTful。

原因是上面的GET请求不是RESTful API范例的一部分。这是一个基本的HTTP GET请求,它产生非JSON内容类型响应,并且该响应不代表RESTful资源的状态。

这只是URL语义,并没有真正改变任何东西,但是当你开始将东西混合到混合API中时,你确实会遇到这些问题。

但是,现在我已经添加了身份验证,这不再有效,因为浏览器在获取文档时不在请求中包含身份验证令牌。

不,它工作正常。这是服务器产生401未经授权的响应。

我明白你在说什么。 <a>标记不再允许您下载URL,因为该URL现在需要身份验证。话虽如此,服务器在可以提供任何一个的上下文中要求对GET请求进行HEADER身份验证时有点奇怪。这不是您的经历所特有的问题,因为我经常看到这种情况发生。这是切换到JWT令牌的思维方式,并认为这可以解决所有问题。

使用createObjectURL()将响应变异到一个新窗口是一种具有其他副作用的黑客攻击。如弹出窗口阻止程序,浏览器历史记录变异以及用户无法查看下载,中止下载或在浏览器的下载历史记录中查看。您还必须想知道下载在浏览器中消耗的所有内存,并且切换到base64只会增加内存消耗。

您应该通过修复服务器的身份验证来解决问题。

<a href="https://my-server.com/my-api/document?id=3&auth=XXXXXXXXXXXXXXXXXXXX">Download</a>

混合RESTful API值得采用混合身份验证方法。

© www.soinside.com 2019 - 2024. All rights reserved.