Request Image Files with Angular 5 and an Bearer Access Token

20 Dec

This post has been updated to support the new HttpClientModule .

When using a full-fledged framework like Angular 5 to talk to your server with AccessTokens, you might not use cookies. In this case, any image requests to your server with an <img />  tag will fail if these need to be authorized.

I have coded a little UrlService and a pipe to help you out. You will need to adapt to your services.

The Service

This code will allow you to request an image with your access token, then return Observable<string>  which will contain a Blob URL. This is using the FileAPI with the method createObjectURL.

Notice also that we return a function for revoking the URL. This way, we avoid memory leaks.

With Angular 5, I would also recommend that you do not hook the getHeaders() token in this service but use an interceptor.

The Pipe

Let’s create a pipe that uses the service above. I have adapted the “async” pipe so you don’t have to write | secure | async  all the time.

You will notice that this pipe is not pure. But the main code is in internalTransform() . We will check if you ask for a different Url, if not, we will not make multiple GET request to your server.

We also use the DomSanitizer because Angular will complain that the blob scheme is unsafe.

Register Services and Pipes

Yep, don’t forget to do that…

The HTML

Simply use the secure pipe like this

Make sure to use the [src]  since you are not actually returning a string but a “ SafeUrl “. Your image is now requested through your UrlHelper service with an access token!

 

Jean-Sébastien Goupil (11 Posts)

Web Architect Consultant - Passionate about web projects! Expert in barcodes, automation, and JavaScript