Get error 401 on images on WP Rest API


#1

Hello,

I’m using a basic authentication in my app to load articles of my wordpress which is locked with authentication.
I’ve used HttpHeaders but I don’t know why, every image returns a 401 error (unauthorized).

I thought it was a CORS issue until I tried on every browser, device and used a plugin to allow CORS on Chrome.

Here is the code that get the articles :

get(query: string = '') {

    let username = "test";
    let password = "test";
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': 'Basic ' +
          btoa(username + ':' + password)
      })
    };

    return this.http.get(this.API_URL + query, httpOptions);
  }

and the code in home.html that fails to load
<img src="{{ item._embedded['wp:featuredmedia'][0].media_details.sizes.medium.source_url }}" />

It always shows this

Can anyone help ? Thank you


#2

Try:

get(query: string = '') {

    let username = "test";
    let password = "test";
    let headers:HttpHeaders = new HttpHeaders({
        'Authorization': 'Basic ' +
          btoa(username + ':' + password)
    });

    return this.http.get(this.API_URL + query, { headers: headers } );
  }

#3

hello, thank you but actually the headers work, it’s just with the images


#4

Your get method with its authorization is totally irrelevant to the way you are fetching images. If you insist on protecting the images behind an authorization barrier, then you need to be responsible for managing the image fetching yourself. You cannot expect <img src="protected-url"> to know how to deal with authorization.