使用CSRF的Apache客户端发布Json 403 Forbidden

时间:2015-12-09 00:24:49

标签: java httpclient

我有一台带有X-CSRF-Token的服务器。 我创建应用程序以从服务器获取_csrf UUID,然后登录 我成功登录服务器。 当我使用GetMethod并发送数据/查询时,我收到了响应。 但我必须将json数据发送到服务器。 当我使用PostMethod时,我会收到POST表单帖子:HTTP / 1.1 403 Forbidden。 我从浏览器测试了我的服务器,收到了很好的数据。 这是来自浏览器的代码

     <input type="button" name="Nazad"
         value="POST DATA" onClick="test()" />


     function test(){
         $.ajax({
             type: "POST",
             url: "${pageContext.request.contextPath}/sifrarnik/global/Vrsta_Tarife/listaVrstaTarifeKasa",
             dataType: "html",
             data: {

             }
         }).done(function(data) {
            if (data != "OK") {
                 $("#validateTips").html("Podatak nije upisan!");
                return;
            }

         });
     };

这是带有loadPage的类并从元标记中获取_csrf, loginPage,其中发送凭据和postQuery以接收json数据

        public static class HttpClientFrame extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 640064664061L;
    private JComboBox cmbURL;     
    private JTextArea taTextResponse;
    private JEditorPane htmlPane;

    private HttpClient client;

    public HttpClientFrame() {            
        client = new HttpClient(new MultiThreadedHttpConnectionManager());
        client.getHttpConnectionManager().
            getParams().setConnectionTimeout(30000);
        client.getParams().setParameter("locale", "sr_LATN_RS");
        JPanel panInput = new JPanel(new FlowLayout());

        String[] aURLs = {
            "http://localhost:8080/MyServer",
            "http://localhost:8080/MyServer/logout",
            "http://localhost:8080/MyServer/user",
            "http://localhost:8080/MyServer/sifrarnik/global/Vrsta_Tarife/listaVrstaTarifeKasa"
        };

        final JButton btnGET = new JButton("GET");
        btnGET.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    String url = (String) cmbURL.getSelectedItem();
                    if (url != null && url.length() > 0) {
                        loadPage(url);
                    }
                }
            }
        );


        final JButton btnPost = new JButton("POST");
        btnPost.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    String url = (String) cmbURL.getSelectedItem();
                    if (url != null && url.length() > 0) {
                        loginPage(url);
                    }
                }
            }
        );


        final JButton btnPost1 = new JButton("POST-1");
        btnPost1.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    String url = (String) cmbURL.getSelectedItem();
                    if (url != null && url.length() > 0) {
                        postJsonQuery(url);
                    }
                }
            }
        );

        cmbURL = new JComboBox(aURLs);
        cmbURL.setToolTipText("Enter a URL");
        cmbURL.setEditable(true);
        cmbURL.setSelectedIndex(0);

        JLabel lblURL = new JLabel("URL:");

        panInput.add(lblURL);
        panInput.add(cmbURL);
        panInput.add(btnGET);
        panInput.add(btnPost);
        panInput.add(btnPost1);


        taTextResponse = new JTextArea();
        taTextResponse.setEditable(false);
        taTextResponse.setCaretPosition(0);

        htmlPane = new JEditorPane();
        htmlPane.setContentType("text/html");
        htmlPane.setEditable(false);

        JSplitPane splitResponsePane = new JSplitPane(
            JSplitPane.HORIZONTAL_SPLIT,
            new JScrollPane(taTextResponse),
            new JScrollPane(htmlPane)
        );
        splitResponsePane.setOneTouchExpandable(false);
        splitResponsePane.setDividerLocation(350);
        // it would be better to set resizeWeight, but this method does
        // not exist in JRE 1.2.2
     //            splitResponsePane.setResizeWeight(0.5);


        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(panInput, BorderLayout.NORTH);
        this.getContentPane().add(splitResponsePane, BorderLayout.CENTER);
    }

    /**
     * Sets the HTML content to be displayed.
     * 
     * @param content an HTML document
     */
    private void setDocumentContent(String content) {

        HTMLDocument doc = new HTMLDocument();
        try {
            doc.remove(0, doc.getLength());
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);

        try {
            htmlPane.read(new ByteArrayInputStream(content.getBytes()), doc);
        } catch (IOException e) {
            e.printStackTrace();
        }

        htmlPane.setDocument(doc);
        htmlPane.setCaretPosition(0);

        taTextResponse.setText(content);
        taTextResponse.setCaretPosition(0);
        taTextResponse.requestFocus();
    }

    /**
     * Loads the page at the given URL from a separate thread.
     * @param url
     */
    private void loadPage(final String url) {
         GetMethod get = new GetMethod(url);
         get.setFollowRedirects(true);
         try {
            int iGetResultCode = client.executeMethod(get);
             final String strGetResponseBody = get.getResponseBodyAsString();

             if (strGetResponseBody != null) {

                    if (strGetResponseBody.contains("<meta name=\"_csrf\"")) {
                        int pos = strGetResponseBody.indexOf("content");
                        csrf = strGetResponseBody.substring(pos + 9, pos + 9 + 36);//strGetResponseBody.lastIndexOf("\""));
                    }
                    if (strGetResponseBody.contains("<meta name=\"_csrf_header\"")) {
                        int pos = strGetResponseBody.indexOf("content");
                        csrf_header = strGetResponseBody.substring(pos + 9, pos + 9 + 12);//strGetResponseBody.lastIndexOf("\""));
                    }

                     NameValuePair _csrf = new NameValuePair("_csrf", csrf);
                     NameValuePair _csrf_header = new NameValuePair("_csrf_header", "X-CSRF-Token");

            client.getParams().setParameter("_csrf", csrf);
            client.getParams().setParameter("_csrf_header", "X-CSRF-Token");
            setDocumentContent(strGetResponseBody);
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
         finally {
            get.releaseConnection();

        }

    }
    private void loginPage(final String url) {
        PostMethod authpost = new PostMethod("http://localhost:8080/MyServer/j_spring_security_check");
        authpost.setDoAuthentication(true);
       // post.setFollowRedirects(true);
                try {
                        // Prepare login parameters
                    NameValuePair action   = new NameValuePair("action", "login");
                    NameValuePair loginUrl      = new NameValuePair("url", "http://localhost:8080/MyServer/j_spring_security_check");
                    NameValuePair userid   = new NameValuePair("j_username", "a");
                    NameValuePair password = new NameValuePair("j_password", "a");
                    NameValuePair _csrf = new NameValuePair("_csrf", csrf);
                    NameValuePair _csrf_header = new NameValuePair("_csrf_header", "X-CSRF-Token");

                    authpost.setRequestBody( 
                      new NameValuePair[] {action, loginUrl, userid, password, _csrf});

                    client.getParams().setParameter("_csrf", csrf);
                    client.getParams().setParameter("_csrf_header", "X-CSRF-Token");

                  HttpClientParams params    = new HttpClientParams();
                  List<String>     authPrefs = new ArrayList<String>(2);

                  authPrefs.add(AuthPolicy.DIGEST);
                  authPrefs.add(AuthPolicy.BASIC);
                  params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                  params.setAuthenticationPreemptive(true);

                  client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

              Credentials credentials = (Credentials) new UsernamePasswordCredentials("a", "a");
              client.getState().setCredentials(AuthScope.ANY, credentials);


                    client.executeMethod(authpost);
                    System.out.println("Login form post: " + authpost.getStatusLine().toString()); 
                    // release any connection resources used by the method
                    authpost.releaseConnection();

                    // Usually a successful form-based login results in a redicrect to 
                    // another url
                    int statuscode = authpost.getStatusCode();
                    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
                        (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
                        (statuscode == HttpStatus.SC_SEE_OTHER) ||
                        (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                        Header header = authpost.getResponseHeader("location");
                        if (header != null) {
                            String newuri = header.getValue();
                            if ((newuri == null) || (newuri.equals(""))) {
                                newuri = "/";
                            }
                            System.out.println("Redirect target: " + newuri); 
                            GetMethod redirect = new GetMethod(newuri);

                            client.executeMethod(redirect);
                            System.out.println("Redirect: " + redirect.getStatusLine().toString()); 
                            // release any connection resources used by the method
                            redirect.releaseConnection();
                        } else {
                            System.out.println("Invalid redirect");
                            System.exit(1);
                        }
                    }   

                    authpost = new PostMethod(url);
                    int iGetResultCode = client.executeMethod(authpost);
                    final String strGetResponseBody = authpost.getResponseBodyAsString();

                    if (strGetResponseBody != null) {
                        // set the HTML on the UI thread
                        SwingUtilities.invokeLater(
                            new Runnable() {
                                public void run() {
                                    setDocumentContent(strGetResponseBody);
                                }
                            }
                        );
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    authpost.releaseConnection();
                }
    }

    private void postJsonQuery(final String url) {
        // create a new thread to load the URL from
        PostMethod post = new PostMethod("http://localhost:8080/MyServer/sifrarnik/global/Vrsta_Tarife/listaVrstaTarifeKasa");
        post.setDoAuthentication(false);
        post.setFollowRedirects(false);
        post.addRequestHeader("Content-Type", "application/json");
        post.addRequestHeader("_csrf", csrf);

        new Thread() {
            public void run() {
                try {

                  HttpClientParams params    = new HttpClientParams();

                  params.setParameter("_csrf", csrf);
                  params.setParameter("_csrf_header", "X-CSRF-Token");
                  client.setParams(params);

                  post.setParameter("_csrf", csrf);
                  post.setParameter("_csrf_header", "X-CSRF-Token");

                  NameValuePair _csrf = new NameValuePair("_csrf", csrf);
                  NameValuePair _csrf_header = new NameValuePair("_csrf_header", "X-CSRF-Token");

                  post.setRequestBody( 
                    new NameValuePair[] {_csrf, _csrf_header});


                client.getParams().setParameter("_csrf", csrf);
                client.getParams().setParameter("_csrf_header", "X-CSRF-Token");


                  client.executeMethod(post);
                  System.out.println("POST  form post: " + post.getStatusLine().toString()); 
                    // release any connection resources used by the method
     //                        post.releaseConnection();



                    // Usually a successful form-based login results in a redicrect to 
                    // another url
                    int statuscode = post.getStatusCode();
                    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
                        (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
                        (statuscode == HttpStatus.SC_SEE_OTHER) ||
                        (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                        Header header = post.getResponseHeader("location");
                        if (header != null) {
                            String newuri = header.getValue();
                            if ((newuri == null) || (newuri.equals(""))) {
                                newuri = "/";
                            }
                            System.out.println("Redirect target: " + newuri); 
                            GetMethod redirect = new GetMethod(newuri);

                            client.executeMethod(redirect);
                            System.out.println("Redirect: " + redirect.getStatusLine().toString()); 
                            // release any connection resources used by the method
                            redirect.releaseConnection();
                        } else {
                            System.out.println("Invalid redirect");
                            System.exit(1);
                        }
                    }   

                    int iGetResultCode = client.executeMethod(post);
                    final String strGetResponseBody = post.getResponseBodyAsString();
                    if (iGetResultCode == HttpStatus.SC_OK) {

                        Vrsta_TarifeBean[] vrstaTarifeBean = new Gson().fromJson(strGetResponseBody, Vrsta_TarifeBean[].class);
                        String ssstrGetResponseBody = vrstaTarifeBean[0].getIdvrsta_tarife().toString();
                        setDocumentContent(ssstrGetResponseBody);
                    }    
                    if (strGetResponseBody != null) {
                        // set the HTML on the UI thread
                        SwingUtilities.invokeLater(
                            new Runnable() {
                                public void run() {
                                    setDocumentContent(strGetResponseBody);
                                }
                            }
                        );
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    post.releaseConnection();
                }
            }
        }.start();
    }        



}




      }

这是我的服务器发送的内容 [{ “ID”:1, “vrsta”: “B”},{ “ID”:2 “vrsta”: “O”},{ “ID”:3 “vrsta”: “P”}] < / p>

我需要在标题postMethod中添加什么内容?

1 个答案:

答案 0 :(得分:0)

已解决的问题 代替          client.getParams()。setParameter(“_ csrf”,csrf);          client.getParams()。setParameter(“_ csrf_header”,“X-CSRF-Token”);

我把它放了           post.addRequestHeader( “X-CSRF令牌”,CSRF); 我没有403错误