AJAX: JWT auth for video load via src

2019-07-17 19:11发布

问题:

I am requesting a video from an API that requires JWT web tokens:

    // when the ajax call is done (the tolken is recieved )
    getAccessToken.done(function(data) {


        var d = JSON.stringify({'fpath': fpath})
        // get the download url
        var downloadurl = $.ajax({
            type: "POST",
            url: "https://gcp.inbcu.com/download",
            beforeSend: function(xhr){
                xhr.setRequestHeader("Authorization", "JWT " +  data.access_token);
            },
            contentType: 'application/json',
            data: d,
            success: function(response){
                $('#video-source').attr('src', response.url)
                $('#myvideo').load()
            },
            error:function(jqXHR, textStatus, errorThrown) {
                console.log("request for download url failed: ", textStatus, errorThrown, jqXHR);
            },
            dataType: 'json'
        });

This ajax call itself is successful (200) and returns the proper values. Mainly it returns a url to set the source of the video.

Problem is, the video src attempts to access the url and doesn't have permission (no jwt token/ authorization). How am I supposed to load the video with the proper permission when loading the src of a video? Is this possible?

回答1:

As the answer to a similar question explains, this isn't possible. Either you need to do it as an AJAX request, which you previously did, but which was slow, or, you need to add additional methods for the server to accept authentication.

Regarding these auth options, you could add a session cookie that the server can check, or append the token to the video url, like response.url + '?token=' + token.



回答2:

A service worker would be capitabel of adding the auth token. But that only solves the problem for FF & Blink