Gar*_*ill 10 http-headers auth-token openid-connect angular
我有一个 Web 应用程序,其中 Angular (7) 前端与服务器上的 REST API 通信,并使用 OpenId Connect (OIDC) 进行身份验证。我正在使用向我的 HTTP 请求HttpInterceptor
添加Authorization
标头以向服务器提供身份验证令牌。到现在为止还挺好。
但是,除了传统的 JSON 数据,我的后端还负责即时生成文档。在添加身份验证之前,我可以简单地链接到这些文档,如下所示:
<a href="https://my-server.com/my-api/document?id=3">Download</a>
Run Code Online (Sandbox Code Playgroud)
但是,现在我已经添加了身份验证,这不再有效,因为浏览器在获取文档时没有在请求中包含身份验证令牌 - 所以我401-Unathorized
从服务器得到了响应。
因此,我不能再依赖普通的 HTML 链接——我需要创建自己的 HTTP 请求,并显式添加身份验证令牌。但是,我如何确保用户体验与用户单击链接时的体验相同?理想情况下,我希望使用服务器建议的文件名保存文件,而不是通用文件名。
Gar*_*ill 10
我拼凑了一些“在我的机器上工作”的东西,部分基于这个答案和其他类似的答案——尽管我的努力是通过打包为可重用指令来“角度化”的。它没有太多内容(大部分代码都在做一些繁重的工作,即根据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);
}
}
Run Code Online (Sandbox Code Playgroud)
其用法如下:
<a downloadFile="https://my-server.com/my-api/document?id=3">Download</a>
Run Code Online (Sandbox Code Playgroud)
……或者,当然:
<a [downloadFile]="myUrlProperty">Download</a>
Run Code Online (Sandbox Code Playgroud)
请注意,我没有在此代码中将身份验证令牌显式添加到 HTTP 请求中,因为我的实现(未显示)已经处理了所有 HttpClient
调用HttpInterceptor
。要在没有拦截器的情况下执行此操作,只需向请求添加标头(在我的情况下为Authorization
标头)。
值得一提的另一件事是,如果被调用的 Web API 位于使用 CORS 的服务器上,则可能会阻止客户端代码访问内容处置响应标头。要允许访问此标头,您可以让服务器发送一个适当的access-control-allow-headers
标头。
归档时间: |
|
查看次数: |
9343 次 |
最近记录: |