Search code examples
javascriptauthenticationheaderxmlhttprequestoauth-2.0

Load image behind oauth2-authentication


I develop a JavaScript application which uses oauth2 authentication. Now I want to load/show an image from server which is behind this authentication mechanism. Therefor I send an xmlHttp-request to the rest-server and get the URI of the image as response.

After the request I try to append the URI to the src of an image and the application responds with 401.

How can I tell the browser to reuse my authentication for this image as well?

This is a part of the xmlHttp-request for getting the URI.

var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);

xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.setRequestHeader('Authorization','bearer '+token);
xhr.send(null); 

xhr.onreadystatechange = function() {
    console.log(xhr);
    if (xhr.readyState == 4 && xhr.status == 200) {
       var img = document.createElement('img');
       img.src = xhr.responseURL;
       document.body.appendChild(img);
    }
}

Did I forgot something?


Solution

  • An image is a static file and I doubt you're going to be able to get OAuth2 protection when you request it via a simple URL. While you can add OAuth2 information in your URL that's probably not a good thing to do because it will expose to the client all the data which should be private and secure.

    Maybe you can consider serving the image from a normal protected endpoint as a byte[] or Base64 string which you can then render in your client if you really need to protect the image itself.

    So have a protected endpoint which serves the content of the image itself. Of course, you'd only do this if you actually need the image to be private and secure. If you don't then just let it be public and serve from a separate CDN. It doesn't really need to be behind an OAuth2 system.