1 year ago

#339758

test-img

TRUSTMEIMJEDI

video player for angular with jwt support

I'm trying to stream video in chunks from Spring boot microservice to Angular frontend app. Video source is secured with JWT, so when sending request for video there is need to pass JWT token to this request.

Example get request for video:

GET http://localhost:8080/api/stream-service/video/${this.videoPath} 
with headers: Authorization: Bearer xxxx

here is example how I'm trying to achieve this

import { AfterViewInit, Component, ElementRef, Inject, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SomeResponse } from '../../models';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-some-info-dialog',
  templateUrl: './some-dialog.component.html',
  styleUrls: ['./some-dialog.component.css']
})
export class SomeDialogComponent implements AfterViewInit {

  @ViewChild('videoPlayer') videoPlayer: ElementRef;
  readonly mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
  readonly some: SomeResponse;
  readonly someVideoUrl;

  constructor(private http: HttpClient,
              private dialogRef: MatDialogRef<SomeDialogComponent>,
              @Inject(MAT_DIALOG_DATA) data) {
    this.some = data.some;
    this.someVideoUrl = `http://localhost:8080/api/stream-service/video/${this.some.videoPath}`;
  }

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

  private sourceOpen(mediaSource): Subscription {
    const sourceBuffer = mediaSource.addSourceBuffer(this.mimeCodec);
    return this.http
      .get(this.someVideoUrl, { responseType: 'blob' })
      .subscribe(blob => {
        sourceBuffer.addEventListener('updateend', () => {
          mediaSource.endOfStream();
          this.videoPlayer.nativeElement.play();
        });
        blob.arrayBuffer().then(x => sourceBuffer.appendBuffer(x));
      });
  }

}

Every request through httpClient is intercepted and JWT token is added before it reach the video resource server.

<video style="width: 100%" controls #videoPlayer>
  Browser not supported
</video>
<h2> {{ some.name }}</h2>
<h3>Opis</h3>
<p> {{ some.description }}</p>
<p> {{ some.test1 }}</p>
<p> {{ some.test2 }}</p>

Following solution is working when I'm using endpoint that is not secured with JWT. Does somebody know how to get video from streaming API that is secured with JWT token?

angular

jwt

video-player

0 Answers

Your Answer

Accepted video resources