本文介绍了使用ANGING从安全端点流式传输视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已保护终结点。我需要从ANGLE在http GET请求的头部传递一个JWT令牌来流式传输视频。

DotNet核心控制器中的端点如下所示(简化):

[Route("api/GetVideo/{videoId}")]
public async Task<IActionResult> GetVideoAsync(int videoId)
{
    string videoFilePath = GiveMeTheVideoFilePath(videoId);

    return this.PhysicalFile(videoFilePath, "application/octet-stream", enableRangeProcessing: true);
}

角度代码:Video.Component.html

<video width="100%" height="320" crossorigin="anonymous" controls #videoElement>
        <source
            [src]="'http://mydomain/api/GetVideo/1' | authVideo | async"  type="application/octet-stream"
        />
</video>

Video.pipe.ts

@Pipe({
    name: 'authVideo',
})
export class AuthVideoPipe implements PipeTransform {
    constructor(private http: HttpClient, private auth: AuthTokenService) {}

    transform(url: string) {
        return new Observable<string>(observer => {
            const token = this.auth.getToken(); //this line gets the jwt token
            const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });

            const { next, error } = observer;

            return this.http.get(url, { headers, responseType: 'blob' }).subscribe(response => {
                const reader = new FileReader();
                reader.readAsDataURL(response);
                reader.onloadend = function() {
                    observer.next(reader.result as string);
                };
            });
        });
    }
}

它确实使用上面的代码向端点发出GET请求。并将某些内容返回到前端。但是视频没有播放。我从这个SO question找到了上面的方法。它适用于图像,但显然不适用于视频。我的想法是,我可能需要在前端逐个字节地读取流。如果是,我该如何操作?

我已尝试将两端的";application/octet-stream";更改为";video/mp4";。但是运气不好。

请注意,当我从后端删除安全代码,并从html删除authVideo管道时,它可以很好地工作。请给我点光。谢谢!

推荐答案

此解决方案适用于图像,因为所有数据都作为数据URL加载一次,但您不应该对视频执行此操作,因为它会禁用浏览器的流功能。实际上,这样做是在将整个视频加载到内存,然后将其转换为数据URL,这在性能和用户体验方面非常糟糕(需要在播放之前加载完整的视频,并且会导致大量内存消耗)。

您问题的明显解决方案是使用Cookie进行身份验证:

  • 鉴权成功时设置cookie
  • 后续请求自动发回,包括视频请求

在下面的内容中,我假设您由于某些原因不能这样做。

您可以使用MediaSource。它允许您控制实际发送的检索视频的请求(并添加Authorization头)。请注意,即使所有浏览器都广泛支持此功能,这也只是试验性的。

您的代码应该如下所示:

assetURL = 'http://mydomain/api/GetVideo/1';

// Modify this with the actual mime type and codec
mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

@ViewChild("videoElement") video: ElementRef;

ngAfterViewInit() {
  if (
    "MediaSource" in window &&
    MediaSource.isTypeSupported(this.mimeCodec)
  ) {
    const mediaSource = new MediaSource();
    (this.video.nativeElement as HTMLVideoElement).src = URL.createObjectURL(
      mediaSource
    );
    mediaSource.addEventListener("sourceopen", () =>
      this.sourceOpen(mediaSource)
    );
  } else {
    console.error("Unsupported MIME type or codec: ", this.mimeCodec);
  }
}

sourceOpen(mediaSource) {
  const sourceBuffer = mediaSource.addSourceBuffer(this.mimeCodec);
  const token = this.auth.getToken(); //this line gets the jwt token
  const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });
  return this.http
    .get(this.assetURL, { headers, responseType: "blob" })
    .subscribe(blob => {
      sourceBuffer.addEventListener("updateend", () => {
        mediaSource.endOfStream();
        this.video.nativeElement.play();
      });
      blob.arrayBuffer().then(x => sourceBuffer.appendBuffer(x));
    });
}

working demo得出以下结果:

这篇关于使用ANGING从安全端点流式传输视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 17:17