0

I'm developing a HTTP filter that redirects to another URL when some image is requested, but the other URL that the new image is, needs authentication. I'm using AEM DAM to store all images. So when the code requests an image locally, the code needs to redirect to DAM and log in, but I can't log in using the code as it is implemented:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    // ==> /images/path/my-image.png
    // ==> /path1/path2/image.pngs
    String servletPath = req.getServletPath();

    // The path to the root directory of the webapp (WebContent)
    //String realRootPath = request.getServletContext().getRealPath("");
    String realRootPath = "http://localhost:4502/crx/de/index.jsp#/content/dam/";

    // Real path of Image.
    String imageRealPath = realRootPath + servletPath;

    System.out.println("imageRealPath = " + imageRealPath);

    File file = new File(imageRealPath);

    // Check image exists.
    if (file.exists()) {
        // Go to the next element (filter or servlet) in chain
        chain.doFilter(request, response);
    } else if (!servletPath.equals(this.notFoundImage)) {
        // Redirect to 'image not found' image.
        HttpServletResponse resp = (HttpServletResponse) response;
        // ==> /ServletFilterTutorial + /images/image-not-found.png
        resp.sendRedirect(req.getContextPath()+ this.notFoundImage);
    }
}
andreybleme
  • 689
  • 9
  • 23
  • _crx/de/index.jsp#_ does not look right in _realRootPath_. Are you developing the filter in AEM or a separate application? For the first case, you can write SlingFilter using service resource resolver with proper rights to read the DAM assets and returning your image data in response. For the second case, AEM provides REST API that can be utilized using [cURL](http://www.aemcq5tutorials.com/tutorials/adobe-cq5-aem-curl-commands/) and corresponding [Java implementation](https://stackoverflow.com/questions/3283234/http-basic-authentication-in-java-using-httpclient) to access your asset. – Kamil Ciecierski Jul 30 '17 at 10:45

1 Answers1

0

AEM supports basic authentication. So, while calling DAM asset URL, then pass username/password.

byte[] authEncBytes = Base64.encodeBase64("admin:admin".getBytes());
String authStringEnc = new String(authEncBytes);         
URL url = new URL("http://localhost:4502/content/dam/myassets/test.jpg");
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + 
         authStringEnc);
        InputStream is = urlConnection.getInputStream();
Pakira
  • 1,951
  • 3
  • 25
  • 54