2017-04-13 5 views
0

Jsoup API를 사용하여 JIRA에 로그인하려했지만 어떤 이유로 작동하지 않습니다.Jsoup를 사용하여 JIRA 로그인을 수행하는 방법은 무엇입니까?

나는 사용자 이름과 암호 태그를 식별하려고했지만 여전히 좋지 않습니다.

누군가 내가 잘못하고있는 것을 알아낼 수 있습니까?

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 = "[email protected]"; 
    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()); 


    } 
} 

JSoup이 아닌 경우 동일한 API를 사용할 수 있습니까?

도움이 될 것입니다.

+0

는 "하지만 여전히 좋은"와 관련된 몇 가지 스택 트레이스 또는 출력을 추가 할 수 있습니까? 결과/오류가 발생 했습니까? – exoddus

+1

jira 's rest api를 사용하지 않는 이유는 무엇입니까? – slowy

+0

Java 용으로 만 사용하도록 요청 받았습니다. –

답변

1

올바른 방향이지만 일부 웹 응용 프로그램의 로그인 프로세스를 가짜로 만들 때 특정 헤더 또는 쿠키 또는 일부 특수 매개 변수를 설정하지 않아서 매우 까다롭거나 성공하지 못할 수 있습니다.

Jira의 documentation을 살펴보면 많은 예제를 발견 할 수 있습니다. 양식으로 사용자 이름과 암호를 보내는 대신 올바른 쿠키를 얻는 데 REST POST를 사용하는 것이 좋습니다.

으로이 문서에서 말했다 :

  • (1) 클라이언트가 JIRA REST API를 통해 사용자에 대한 새 세션을 만듭니다.
  • (2) JIRA는 세션 쿠키를 포함하여 세션에 대한 정보가있는 세션 객체를 반환합니다. 클라이언트는이 세션 객체를 저장합니다.
  • (3) 이제 클라이언트는 JIRA REST API에 대한 모든 후속 요청에 대해 헤더에 쿠키를 설정할 수 있습니다.

내가 그 테스트를위한 간단한 클래스를 만든 내가 락스와 협력을 확보 한 (확실하지 버전하지만 아마도 마지막 기능). 단지 (응답에 나타납니다 성공적인 로그인 fullName의 후) 서버의 응답에 전체 이름을 검색 getFullName 방법 :

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"; 
} 

}