Login into Web portal via Java

352 views Asked by At

My scenario: I am working with an enterprise portal which is closed-source to me , the app provides some reports , I need to show the reports in a TV , so I need to , the TV has a build-in web browser to show html. til here there is no problem but the portal has a log-in page to prevent anonymous access , I have credentials but the TV is going to show reports randomly so I need a mechanism to log-in to the app and then loading a sample report and pass it to TV's browser.

What I've Done: I've created a web page which gets a report's URL and then logs into the portal and after that reads the cookies and then opens a connection to the reports (via it's URL) to load its content and returns back the contents to the browser (TV browser).

My Code

  @WebServlet("/LoadReport")
    public class LoadReport extends HttpServlet {
    private static final long serialVersionUID = 1L;    
    public LoadReport() {
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        HttpSession session = request.getSession(true);     
        session.setMaxInactiveInterval(5);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();     

        if (request.getQueryString() != null && request.getQueryString() != "") {

            String tmp = request.getQueryString();
            tmp = tmp.substring(tmp.indexOf('=') + 1);
            sb.append(tmp);
            String postParams = "j_username=djboobo&j_password=djboobo&persistent=on";

            URL url = new URL("http://xyz/xyz/login/auth.jsp");
            HttpURLConnection connection = (HttpURLConnection) getConnection(postParams, url);
            // get sessionid from cookies 
            String cookies = getCookies(connection, postParams);            
            cookies += "logindetails=username:djboobo&persistent:yes";
            // url to report
            url = new URL(tmp);
            connection = (HttpURLConnection) getConnection(postParams, url);
            connection.setRequestProperty("Cookie", cookies);
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(postParams);          
            wr.flush();

            try {

                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((line = br.readLine()) != null) {                    
                    out.write(line);                    
                }               

            } catch (Exception e) {             
            }
            wr.close();
            connection.disconnect();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // TODO Auto-generated method stub
    }   

    private HttpURLConnection getConnection(String postParams, URL url) throws IOException, ProtocolException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Host", "http://xyz/xyz");
        connection.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.8,fa;q=0.6");
        connection.setRequestProperty("Cache-Control", "max-age=0");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Length", String.valueOf(postParams.getBytes().length));
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("charset", "utf-8");
        connection
                .setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36");

        return connection;
    }

    private String getCookies(HttpURLConnection conn, String postParams) throws IOException {
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        List<String> cookies = conn.getHeaderFields().get("Set-Cookie");
        StringBuilder sb = new StringBuilder();
        for (String cookie : cookies) {
            // System.out.println("Cookies: " + cookie);
            if (cookie.contains("JSESSIONID")) {
                sb.append(cookie.substring(0, cookie.indexOf(";")));
                sb.append("; ");
                break;
            }
        }
        return sb.toString();
    }
    }

What's The Main Problem I tried to use chrome developer tool to find out how portal works and what is it's request and response cookies then I found if I pass SessionId (one of cookies) to the portal it will returns report's content but when I use the SessionId which copied from chrome's tool (mean loged-in from chrome browser) the report's content loading from portal, but when I use SessionId which is come from programmatically log-in the report's content is not getting loaded.

I think the portal logs-in the connection come from program because it returns SessionId but after log-in it kills the Session so the connection to report with the SessionId is not getting authenticated.

what's wrong ???

0

There are 0 answers