Secure Image with Basic Authorization in Angular5

I have the url of a basic resolution image. I need to upload images dynamically. After authorization, the image will be returned as data. How to handle this image with authorization. I am currently trying like this

<img [src]=" getImage(res.imageurl) | async" /> getImage(imageUrl: string): Observable<File> { let headers = new HttpHeaders(); headers = headers.append("Authorization", "Basic " + btoa(this.domain + '/' + logindata.username + ':' + logindata.password)); return this.http .get(imageUrl,{headers:headers}, { responseType: ResponseContentType.Blob }) .map((res: Response) => res.blob()); } 
+5
source share
4 answers

Try using an authorization token instead of a username and password.

how

 @Component({ template: ` <img [src]="img.src + '?bearer=' + bearToken"/> ` }) export class FooComponent { img = { src: 'https://angular.io/assets/images/logos/angular/ logo-nav@2x.png ' } bearerToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; } 

Thus, the link to the image will be created in this way https: //domain/assets/images/xyz.png? Bearer = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ...

+2
source

If you want to use httpclient to load the image data, and then to present it in the image tag, you need base64 to encode the blob you are returning (or base64 on the server side), then pass it to src as the data url , eg:

 <img src="data:image/png;base64,{{encodedImage}}"> 
+1
source

you want to return data from the response, but do not sign it ...

add after .map(...).subscribe(r => {return r;})

and delete return to this.http.get

0
source

You want to implement an interceptor . In your implementation of the intercept () method, you can check the request parameter and see if this is a request for your image.

0
source

Source: https://habr.com/ru/post/1275251/


All Articles