Passing authorization header for images src to remote server in Ionic page Passing authorization header for images src to remote server in Ionic page angular angular

Passing authorization header for images src to remote server in Ionic page


1) Create interceptor which sets authorization header

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';import { Observable } from 'rxjs/Observable';@Injectable()export class AuthInterceptor implements HttpInterceptor {    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        request = request.clone({            setHeaders: {                Authorization: `Bearer <your token>`            }        });        return next.handle(request);    }}

Instead of <your token> you should inject your AuthService into this interceptor, for example this.authService.getToken(), which loads token from local storage.

2) Implement "secure" pipe which gets image as blob and creates an object url of that blob that can be used in the src attribute

import { Pipe, PipeTransform } from '@angular/core';import { HttpClient } from '@angular/common/http';import { DomSanitizer, SafeUrl } from '@angular/platform-browser';import { Observable } from 'rxjs/Observable';@Pipe({    name: 'secure'})export class SecurePipe implements PipeTransform {    constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }    transform(url): Observable<SafeUrl> {        return this.http            .get(url, { responseType: 'blob' })            .map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));    }}

3) Use it

<img [attr.src]="'your link' | secure | async" />


1st Option: Look for "URL signing"

The idea is that, when you use <img src="http://foo.com/image/1"> there is no way to pass the authorization headers. So instead, you make post request to your backend to ask for a temporary public link for the image and put this link as source of image.

Here is an example flow

  1. I need to show "http://foo.com/image/1"

  2. From the browser, make a post request to backend, let them know you are an authorized client (include the authorization header), and ask for a temporary url that will show the image publicly

  3. From the backend, generate a signed url that is valid for a limited time and does not require authorization headers to show the image.

  4. Use the temporary signed url you just received as src of the img tag.

2nd Option: Download the image and use blob URL

Answers to this question will tell you about it: Force HTTP interceptor in dynamic ngSrc request


Here is how you write an interceptor,

  1. Need to extend a class called HttpInterceptor provided in angular 4/5.
  2. Override a method called intercept,

It will add the header in all your http request, this would ideally be the place where you would perhaps need to put sanitation logic, for an example if you wish to put just certain request with that header you can decide that in intercept method.

export class YourInterceptor implements HttpInterceptor{        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{const NewRequest= req.clone({ headers: req.headers.set(‘Auth-Token’, ‘YourAuthToken’) });

return next.handle(NewRequest); }

After this you need to register this in your app.module.ts file in the manner given below,

import { YourInterceptor } from './Your-interceptor';

now go to the @NgModule section and do this in your provider array, it would be to the provider array as given below,

providers: [{provide: HTTP_INTERCEPTORS,useClass: YourInterceptor,multi: true}],

Now restart your app and whatever http call you make it will have a control inside which will intercept your code and you will be able to sail through.