7

Let's assume we have a content provider endpoint here myuri.org/api/auth/sources/{id} which returns music files identified by id.

The route /api/auth/ requires authentication. In this case this is done with a JWT passed in the request header like so Authentication: Bearer <token>.

If the authentication wouldn't be there, I could just load a html5 audio component with the source for a fictional music file with id 37 like so

<audio controls>
  <source src="myuri.org/api/sources/37" type="audio/mp3">
</audio>

But since I need authentication; how would this work? And for any possible solution provided; does seeking/skipping still work?

2 Answers 2

6

.. I spent some more time searching for other answers and found this post. I guess this is not possible this way.

Alternative Solution

The following code is a proof of concept following the described logic. But instead of using the html5 audio component, it uses the Web Audio Api.

let url = "myuri.org/auth/sources/37";

// create context
let audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create source
let source = audioCtx.createBufferSource();

// route source
source.connect(audioCtx.destination);

// prepare request
let request = new XMLHttpRequest();
request.open('GET', url, true /* async */ );
request.responseType = 'arraybuffer';

request.onload = function () {
    // on load callback

    // get audio data
    let audioData = request.response;

    // try to decode audio data
    audioCtx.decodeAudioData(audioData,
        function (buffer) {
            // on success callback
            console.log("Successfully decoded");

            // set source
            source.buffer = buffer;

            // .. do whatever you want with the source
            // e.g. play it
            source.start(0);
            // or stop
            source.stop();
        },
        function (e) {
            // on error callback
            console.log("An error occurred");
            console.log(e);
        });
};

request.setRequestHeader("Authorization", `Bearer ${authenticationToken}`);
request.send();

I hope this helps someone.

2

1

Or if you can change the backend then you can make it read jwt from query string:

https://myuri.org/api/sources/37?jwt={jwt}

In my case it was Django (Rest Framework)

# auth.py
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

class QSJSONWebTokenAuthentication(JSONWebTokenAuthentication):
    def get_jwt_value(self, request):
        return request.query_params.get('jwt', '')

# views.py
class AudioView(generics.RetrieveAPIView):
    authentication_classes = (QSJSONWebTokenAuthentication,)

    def retrieve(self, request: Request, *args, **kwargs):
        pass

2

Another strategy also depends on whether you have control over backend:

send request to the server and ask for temporary url of file, use that url in <audio>. Storage providers such as Google Storage or S3 have api that allows to generate url with which everyone will have access to the file for short period of time. You can also implement something similar yourself using JWT (one token for auth in first request and second token for file access verification)

2
  • I thought of this, but isn't this a security issue because the link might be logged somewhere? Mar 5, 2019 at 18:51
  • if you are concerned about security then you shouldn't use JWT (: It indeed can be logged on server that owns myuri.org but hackers will need to break into that server first and if they do this then leaked tokens will not be the biggest problem here. Also each JWT should have time-to-live param and be refreshed frequently on client, so no one will be able to use old tokens.
    – aiven
    Mar 5, 2019 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.