简体   繁体   English

如何使用Jsoup登录JIRA?

[英]How to do JIRA login using Jsoup?

I've been trying to login to JIRA using the Jsoup API, but it's not working for some reason. 我一直在尝试使用Jsoup API登录JIRA,但是由于某些原因,它无法正常工作。

I've tried to identify the username and password tags, but still no good. 我试图识别用户名和密码标签,但仍然不好。

Can someone please help me figure out what I am doing wrong? 有人可以帮我弄清楚我在做什么错吗?

public class test
{
public static void main(String[] args) throws IOException{
    final String USER_AGENT = "\"Mozilla/5.0 (Windows NT\" +\n" +  
     "          \" 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36\"";  
    String loginFormUrl = "https://jira.aciworldwide.com/login.jsp";  
    String loginActionUrl = "https://jira.aciworldwide.com/login.jsp";  
    String username = "jon@jon";  
    String password = "XXXXXX";  

     HashMap<String, String> cookies = new HashMap<>();  
     HashMap<String, String> formData = new HashMap<>();  

     Connection.Response loginForm = Jsoup.connect(loginFormUrl).method(Connection.Method.GET).userAgent(USER_AGENT).execute();  
     Document loginDoc = loginForm.parse(); // this is the document that contains response html

     cookies.putAll(loginForm.cookies()); // save the cookies, this will be passed on to next request  

     formData.put("login", "Log In"); 
     formData.put("os_username", username);  
     formData.put("os_password", password); 

     Connection.Response homePage = Jsoup.connect(loginActionUrl)  
         .cookies(cookies)  
         .data(formData)  
         .method(Connection.Method.POST)  
         .userAgent(USER_AGENT)  
         .execute();  

     System.out.println(homePage.parse().html());  


   }
}

If not JSoup, is there any other API available for the same? 如果不是JSoup,是否还可以使用其他API?

Any help would be greatly appreciated! 任何帮助将不胜感激!

You are in the right direction but sometimes "faking" the login process of some webapps can be quite tricky or hard to success because you are missing to set one specific header, or cookie, or some special param... 您的方向是正确的,但有时“伪造”某些Web应用程序的登录过程可能非常棘手或难以成功,因为您缺少设置一个特定的标头,Cookie或某些特殊的参数...

If you take a look at Jira's documentation you'll find many examples. 如果您查看Jira的文档 ,则会发现许多示例。 Instead of sending the username and password as a form, you better do a REST POST for getting a valid cookie. 与其发送用户名和密码作为表单,不如执行REST POST以获得有效的cookie。

As said in documentation: 如文档中所述:

  • (1) The client creates a new session for the user, via the JIRA REST API . (1)客户端通过JIRA REST API为用户创建一个新会话。
  • (2) JIRA returns a session object, which has information about the session including the session cookie. (2)JIRA返回一个会话对象,该对象具有有关会话的信息,包括会话cookie。 The client stores this session object. 客户端存储该会话对象。
  • (3) The client can now set the cookie in the header for all subsequent requests to the JIRA REST API. (3)客户端现在可以在头中为对JIRA REST API的所有后续请求设置cookie。

I've created a simple class for testing that and I've ensured is working with Jira (not sure what's the version but probably the last one). 我创建了一个简单的类进行测试,并且确保与Jira一起使用(不确定版本是什么,但可能是最后一个)。 The method getFullName just search for the fullName on the server's response (after successfull login fullName will appear in the response): 方法getFullName只是在服务器的响应中搜索fullName(成功登录后,fullName将出现在响应中):

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

public class JiraLogin {

private final static String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
private final static String JIRA_REST_LOGIN = "https://youdomain.com/rest/auth/1/session";

private final static String HOME_URL = "https://youdomain.com/";
private final static String USERNAME = "your_username";
private final static String PASSWORD = "your_password";

public static void main(String[] args) throws IOException {
    JiraLogin app = new JiraLogin();
    app.doLogin();
}

public void doLogin() throws IOException {
    // (1)
    Response postResult = doLoginPost();
    System.out.println("POST credentials result: " + postResult.body());
    // (2)
    Map<String, String> cookies = postResult.cookies();

    Document loggedDocument = Jsoup.connect(HOME_URL)
            .cookies(cookies)    // (3)
            .method(Method.GET)
            .userAgent(USER_AGENT)
            .validateTLSCertificates(false)
            .get();

    System.out.println("FullName: " + getFullName(loggedDocument));
}

private Response doLoginPost() throws IOException {
    return Jsoup.connect(JIRA_REST_LOGIN)
            .validateTLSCertificates(false)
            .method(Method.POST)
            // if use regular USER_AGENT gets a 403 error
            // http://stackoverflow.com/questions/10120849/jsoup-connect-throws-403-error-while-apache-httpclient-is-able-to-fetch-the-cont
            .userAgent("Mozilla")
            .ignoreContentType(true)
            .requestBody("{ \"username\": \"" + USERNAME +"\", \"password\": \"" + PASSWORD +"\" }")
            .header("Content-Type", "application/json")
            .execute();
}

private String getFullName(Document document) {
    Optional<Element> fullNameOpt = document.getElementsByTag("meta")
            .stream()
            .filter(e -> e.hasAttr("name") && "ajs-remote-user-fullname".equals(e.attr("name"))).findFirst();

    return fullNameOpt.isPresent() ? fullNameOpt.get().attr("content") : "Not found";
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM