Jos Nieuwenhuis


Servlet code voor het afhandelen van NTLM Authenticatie

Over de java servlet die NTLM authenticatie heb ik al eens geschreven in deze blog post: Connecting to a NTLM Web Service using a Java Servlet. In onderstaande code is de Servlet aangepast voor test-doeleinden. Op de webpagina wordt de configuratie van de Servlet getoond zien inclusief de inhoud van de laatst uitgevoerde request/response. Dus, de GET methode wordt gerbuikt voor het tonen van informatie en de POST methode ontvangt en forward SOAP calls en past de NTLM authenticatie toe.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.*;
import org.apache.http.util.EntityUtils;
/**
 * Proxy Servlet
 */
public class NTLMServlet extends HttpServlet {
    private DefaultHttpClient httpclient = new DefaultHttpClient();
    private String user = "";
    private String password = "";
    private String domain = "";
    private String host = "";
    private int port = 443;
    private String endpoint = "";
    private String environment = "";
    private String message = "";
    private String requestString = "";
    private String responseString = "";
    private Map httppostheaders = new HashMap();
    private Map httppostheaders = new HashMap();
    @Override
    public void init() throws ServletException {
        user = getServletConfig().getInitParameter("user");
        password = getServletConfig().getInitParameter("password");
        domain = getServletConfig().getInitParameter("domain");
        host = getServletConfig().getInitParameter("host");
        endpoint = getServletConfig().getInitParameter("endpoint");
        environment = getServletConfig().getInitParameter("environment");
        try {
            port = Integer.parseInt(getServletConfig().getInitParameter("port"));
        } catch (Exception e) {
            port = 443;
        }
        try {
            httpclient = (DefaultHttpClient) HttpClientWrapper.wrapClient(httpclient);
            httpclient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(host, port, domain),
                    new NTCredentials(user, password, host, domain));
            httpclient.getParams().setParameter(
                    CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
            httpclient.getParams().setParameter(
                    CoreProtocolPNames.PROTOCOL_VERSION,
                    HttpVersion.HTTP_1_1);
            httpclient.getParams().setParameter(
                    CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        } catch (Exception e) {
            message = e.getMessage();
        }
    }
    /**
     * Handles the HTTP <code>POST</code> method. Forwards an incoming request to
     * a remote web service which is protected by NTLM authentication.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = null;
        response.setCharacterEncoding("utf-8");
        out = response.getWriter();
        HttpPost httppost = new HttpPost(endpoint);
        InputStream in = null;
        httppostheaders.clear();
        try {
            in = request.getInputStream();
            Writer writer = new StringWriter();
            char[] buffer = new char[1024];
            Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
            httppost.setEntity(new StringEntity(retrieveInput(writer.toString())));
            Enumeration headernames = request.getHeaderNames();
            while (headernames.hasMoreElements()) {
                String headerName = (String) headernames.nextElement();
                String headerValue = request.getHeader(headerName);
                addHttpPostHeader(httppost, headerName, headerValue);
            }
            Header h1 = httppost.getFirstHeader(HTTP.CONTENT_LEN);
            if (h1 != null) {
                removeHttpPostHeader(httppost,h1);
            }
            Header h2 = httppost.getFirstHeader(HTTP.TARGET_HOST);
            if (h2 != null) {
                removeHttpPostHeader(httppost,h2);
            }
            Header[] contentheaders = httppost.getHeaders(HTTP.CONTENT_TYPE);
            for(Header h: contentheaders) {
                removeHttpPostHeader(httppost,h);
            }
            addHttpPostHeader(httppost,HTTP.TARGET_HOST, host);
            addHttpPostHeader(httppost,HTTP.CONTENT_TYPE, 
                    "application/soap+xml; charset=UTF-8");
            HttpResponse httpresponse = httpclient.execute(
                    new HttpHost(host, port, "https"),
                    httppost,
                    new BasicHttpContext());
            HttpEntity output = httpresponse.getEntity();
            Header[] headers = httpresponse.getAllHeaders();
            for (Header header : headers) {
                if (!header.getName().equals(HTTP.CONTENT_LEN)) {
                    response.setHeader(header.getName(), header.getValue());
                }
            }
            if (output != null) {
                out.write(makeOutput(EntityUtils.toString(output)));
            }
        } catch (Exception e) {
            e.printStackTrace(out);
        } finally {
            in.close();
            out.flush();
            out.close();
        }
    }
    protected String retrieveInput(String string) {
        requestString = string;
        return string;
    }
    protected String makeOutput(String string) {
        responseString = string;
        return string;
    }
    protected void addHttpPostHeader(HttpPost httppost, String headerName, String headerValue) {
        httppostheaders.put(headerName,headerValue);
        httppost.setHeader(headerName, headerValue);
    }
    protected void removeHttpPostHeader(HttpPost httppost, Header header) {
        httppostheaders.remove(header.getName());
        httppost.removeHeader(header);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.write("<html><head><title>Servlet is up</title></head><body>");
        out.write("<table><tr><td>host:</td><td>");
        out.write(host);
        out.write("</td></tr><tr><td>port:</td><td>");
        out.write(port + "");
        out.write("</td></tr><tr><td>");
        out.write("endpoint:");
        out.write("</td><td>");
        out.write(endpoint);
        out.write("</td></tr>");
        out.write("<tr><td>");
        out.write("domain:");
        out.write("</td><td>");
        out.write(domain);
        out.write("</td></tr><tr><td>environment:</td><td>");
        out.write(environment);
        out.write("</td></tr>");
        
        Map headers = httppostheaders;
        Set keys = headers.keySet();
        Iterator keysiterator = keys.iterator();
        while(keysiterator.hasNext()){
            String key = (String) keysiterator.next();
            String value = (String) headers.get(key);
            out.write("<tr><td>");
            out.write(key);
            out.write(":</td><td>");
            out.write(value);
            out.write("</td></tr>");
        }
        out.write("</table>");

        out.write("<table>");
        out.write("<tr><td>");
        out.write("Last request:");
        out.write("</td><td>");
        out.write("<textarea rows=15 cols=80>");
        out.write(requestString);
        out.write("</textarea>");
        out.write("</td></tr><tr><td>");
        out.write("Last response:");
        out.write("</td><td>");
        out.write("<textarea rows=30 cols=80>");
        out.write(responseString);
        out.write("</textarea>");
        out.write("</td></tr></table>");
        out.write(message);
        out.write("</body></html>");
        out.flush();
        out.close();
    }
}
Datum: 16 april 2011 - Java,Java EE

Geen reacties

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.