在Ionic页面中将图像src的授权标题传递给远程服务器

Rag*_*hav 10 cordova typescript ionic-framework angular

我有一个Ionic应用程序,它从远程服务器获取数据并将其显示在Ionic html页面上.

远程URL将如下所示:

http://foo.com/api/content/1

这将给我一个"内容"的JSON对象,并将在Ionic应用程序的html页面中进一步使用.

在Ionic app里面的html页面上使用它是这样的:

<div class="article-desc">
  <p [innerHtml]="myObject?.Body"></p>
</div>
Run Code Online (Sandbox Code Playgroud)

"myObject"是从服务器收到的响应的JSON对象.

"正文"字段包含要在段落中显示的HTML.此"HTML"字段仅与整个"内容"对象一起从服务器返回.

"Body"字段可以包含以下内容:

<p>blah blah <img src="http://foo.com/image/1"/> blah blah <img src="http://foo.com/image/2"/>blah blah blah </p>
Run Code Online (Sandbox Code Playgroud)

您可以从上面的示例中看到该图像存在于该html中.

我没有问题将该字段中的html呈现给Ionic Page.

我有一个问题是我的图像没有在那里呈现.

这就是为什么..

我的应用程序已被访客用户锁定,因此对于每个请求,我需要发送一个Authorization标头以对其进行身份验证,在这种情况下,所有图像都无法呈现,因为每个图像请求都将被视为服务器的访客.

你能建议一个常见的地方,我的所有图像和hmtl中的其他来源都应该通过,并可以将授权标题随之发送到服务器.

我已在本地存储项中拥有授权令牌.

我的目标是在Ionic应用程序中呈现时,在该Body字段中出现的每个外部源(此处为图像)发送授权标头.

Mil*_*nák 34

1)创建设置授权头的拦截器

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            setHeaders: {
                Authorization: `Bearer <your token>`
            }
        });

        return next.handle(request);
    }
}
Run Code Online (Sandbox Code Playgroud)

您应该将AuthService注入此拦截器而不是"您的令牌",并使用例如this.authService.getToken(),它从本地存储加载令牌.

2)实现"安全"管道,将图像作为blob并创建可以在src属性中使用的该blob的对象URL

import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';

@Pipe({
    name: 'secure'
})
export class SecurePipe implements PipeTransform {

    constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

    transform(url): Observable<SafeUrl> {
        return this.http
            .get(url, { responseType: 'blob' })
            .map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));
    }

}
Run Code Online (Sandbox Code Playgroud)

3)使用它

<img [attr.src]="'your link' | secure | async" />
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,谢谢!我使用了您的 SecurePipe 并在调用 http get 之前在转换函数中插入了授权标头。它也起作用了。对于那些不想实现拦截器的人来说,这可能是一种选择。 (3认同)

Has*_*san 6

第一个选项:查找“URL 签名”

这个想法是,当您使用时,<img src="http://foo.com/image/1">无法传递授权标头。因此,您可以向后端发出发布请求,请求图像的临时公共链接,并将此链接作为图像源。

这是一个示例流程

  1. 我需要显示“ http://foo.com/image/1

  2. 从浏览器向后端发出 post 请求,让他们知道您是授权客户端(包括授权标头),并请求一个将公开显示图像的临时 url

  3. 从后端生成一个在有限时间内有效且不需要授权标头即可显示图像的签名 URL。

  4. 使用您刚刚收到的临时签名 URL 作为 img 标签的 src。

第二个选项:下载图像并使用 blob URL

这个问题的答案会告诉你:Force HTTP拦截器在动态ngSrc请求中