title: Return image from web api controller action while authenticated
body: <p>I have a Web api that uses owin authentication with bearer tokens. I will have both web and wpf (vb) clients, that need to ask for image files from the api while authenticated. The images should not be returned on unauthenticated requests.</p>
  
  <p>So far I have a working solution on returning an image while not authenticated: </p>
  
  <p>My controller action in c#: </p>
  
  <pre><code>//[Authorize]
  public HttpResponseMessage GetFile()
  {
      string localFilePath = "C:/Path/ImageOnServerDisk.png";
  
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
      response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
      response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
      response.Content.Headers.ContentDisposition.FileName = "myImage.png";
      response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
  
      return response;
  }
  </code></pre>
  
  <p>And this is how I display it on the web client:</p>
  
  <pre><code>&lt;img src="/api/Secure/GetFile" id="img" /&gt;
  </code></pre>
  
  <p>This works fine, but of course when I uncomment the authorize attribute in the above action, the image file is not shown and I get a 401 (Unauthorized) message for the GET message calling for the GetFile action. This is because there is no access token on the GET request. </p>
  
  <p>I could use jQuery to GET via ajax, but I don't know how to set the result into an img element. </p>
  
  <p>How can I either set the access token for the http GET request calling an action in an img src, or set the image content into the img element in jQuery? Or is there a better way to do this altogether?</p>