Bonjour,

Je cherche actuellement une façon d'implémenter une connexion à un sharepoint (office365). J'ai déjà essayé différentes choses sans succès et j'ai l'impression que je tourne en rond sur des technologies que je ne connais pas bcp.

Pouvez-vous me donner des idées d'implémentations ou même un code déjà fait ?

Merci de l'aide que vous pouvez me donner.


Différents essais :

Là j'obtiens une erreur 403 Forbidden.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
 
import java.io.File;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
/**
 * Hello world!
 *
 */
public class App 
{
	/**
           * download a file from a sharepoint library
           */
	public static void main(String[] args) throws Exception{
 
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
	    credsProvider.setCredentials(
	            new AuthScope(AuthScope.ANY),
	            //"username", "password", "https://hostname", "domain"));
	            new NTCredentials("myUser@myDomain.onmicrosoft.com", "myPassword, "https://myDomain.sharepoint.com/sites/MySharePoint", "myDomain"));
	    CloseableHttpClient httpclient = HttpClients.custom()
	            .setDefaultCredentialsProvider(credsProvider)
	            .build();
	    try {
//	    	HttpGet httpget = new HttpGet("http://myDomain.sharepoint.com/sites/MySharePoint/_api/web/lists");
	    	HttpGet httpget = new HttpGet("http://myDomain.sharepoint.com/sites/MySharePoint/");
 
	        System.out.println("Executing request " + httpget.getRequestLine());
	        CloseableHttpResponse response = httpclient.execute(httpget);
	        try {
	            System.out.println("----------------------------------------");
	            System.out.println(response.getStatusLine());
	            EntityUtils.consume(response.getEntity());
	        } finally {
	            response.close();
	        }
	    } finally {
	        httpclient.close();
	    }
	}
}
J'ai aussi essayé via REST, là j'ai un code 200 mais je ne sais pas comment rajouter la partie de l'authentification
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
 
import javax.net.ssl.HttpsURLConnection;
 
public class RestExample {
 
	public static void main(String[] args) {
 
		try {
			URL url = new URL("https://login.microsoftonline.com/common/oauth2/v2.0/authorize");
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");
 
			String userCredentials = "myUser@myDomain.onmicrosoft.com:MyPassword";
			String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
 
			conn.setRequestProperty ("Authorization", basicAuth);
 
			if(conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : " +conn.getResponseCode());
			} 
 
			System.out.println(conn.getResponseCode());
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
 
			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {
				System.out.println(output);
			}
 
 
 
			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
 
	}
 
}

ou encore cette partie là qui me renvoie une erreur 301 Moved Permanently

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
 
import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.xml.sax.*;
 
public class LoginManager {
	private final String sts = "https://login.microsoftonline.com/extSTS.srf";
	private final String loginContextPath = "/_forms/default.aspx?wa=wsignin1.0";
	private final String sharepointContext = "http://myDomain.sharepoint.com/sites/mySharePoint/";
	private final String username="myUser@myDomain.onmicrosoft.com";
	private final String password="myPassword";
	private final String reqXML = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"><s:Header><a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action><a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo><a:To s:mustUnderstand=\"1\">https://login.microsoftonline.com/extSTS.srf</a:To><o:Security s:mustUnderstand=\"1\" xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><o:UsernameToken><o:Username>[username]</o:Username><o:Password>[password]</o:Password></o:UsernameToken></o:Security></s:Header><s:Body><t:RequestSecurityToken xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\"><wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\"><a:EndpointReference><a:Address>[endpoint]</a:Address></a:EndpointReference></wsp:AppliesTo><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType></t:RequestSecurityToken></s:Body></s:Envelope>";
	private String generateSAML() {
		String saml = reqXML
				.replace("[username]", username);
		saml = saml.replace("[password]", password );
		saml = saml.replace("[endpoint]", sharepointContext+loginContextPath);
		return saml;
	}
	public String login() {
		String token;
		try {
			token = requestToken();
			String cookie = submitToken(token);
			return cookie;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return "";
	}
 
	private String requestToken() throws XPathExpressionException, SAXException,
		ParserConfigurationException, IOException {
 
		String saml = generateSAML();
 
		URL u = new URL(sts);
		URLConnection uc = u.openConnection();
		HttpURLConnection connection = (HttpURLConnection) uc;
 
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("GET");
 
		connection.addRequestProperty("Content-Type",
				"text/xml; charset=utf-8");
		// connection.addRequestProperty("Expect", "100-continue");
		// connection.addRequestProperty("Connection", "Keep-Alive");
		// connection.addRequestProperty("Content-Length", saml.length() +
		// "");
		// connection.setRequestProperty("SOAPAction", SOAP_ACTION);
 
		OutputStream out = connection.getOutputStream();
		Writer wout = new OutputStreamWriter(out);
		wout.write(saml);
 
		wout.flush();
		wout.close();
 
		InputStream in = connection.getInputStream();
		int c;
		StringBuilder sb = new StringBuilder("");
		while ((c = in.read()) != -1)
			sb.append((char) (c));
		in.close();
		String result = sb.toString();
		String token = extractToken(result);
		System.out.println(token);
		return token;
	}
	private String extractToken(String result) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
 
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
 
        Document document = db.parse(new InputSource(new StringReader(result)));
 
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xp = xpf.newXPath();
        String token = xp.evaluate("//BinarySecurityToken/text()", document.getDocumentElement());
        System.out.println(token);
        return token;
	}
	private String submitToken(String token) throws IOException {
		String url = sharepointContext+loginContextPath;
		URL u = new URL(url);
		URLConnection uc = u.openConnection();
		HttpURLConnection connection = (HttpURLConnection) uc;
 
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.addRequestProperty("Accept", "application/x-www-form-urlencoded");
		connection.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
		// http://stackoverflow.com/questions/12294274/mobile-app-for-sharepoint/12295224#12295224
		// connection.addRequestProperty("SOAPAction", sts);
		connection.addRequestProperty("Content-Type",
				"text/xml; charset=utf-8");
		// connection.addRequestProperty("Expect", "100-continue");
		// connection.addRequestProperty("Connection", "Keep-Alive");
		// connection.addRequestProperty("Content-Length", saml.length() +
		// "");
		connection.setInstanceFollowRedirects(false);
 
		OutputStream out = connection.getOutputStream();
		Writer wout = new OutputStreamWriter(out);
 
		wout.write(token);
 
		wout.flush();
		wout.close();
 
		InputStream in = connection.getInputStream();
 
		//http://www.exampledepot.com/egs/java.net/GetHeaders.html
 
	    for (int i=0; ; i++) {
	        String headerName = connection.getHeaderFieldKey(i);
	        String headerValue = connection.getHeaderField(i);
	        System.out.println("header: " + headerName + " : " + headerValue);
	        if (headerName == null && headerValue == null) {
	            // No more headers
	            break;
	        }
	        if (headerName == null) {
	            // The header value contains the server's HTTP version
	        }
	    }
		String headerName = connection.getHeaderField("set-cookie");
		System.out.println("headerName");
		System.out.println(headerName);
		int c;
		StringBuilder sb = new StringBuilder("");
		while ((c = in.read()) != -1)
			sb.append((char) (c));
		in.close();
		String result = sb.toString();
		System.out.println(result);
 
		return headerName;
	}
 
	public static void main(String [] args) {
		System.out.println(new LoginManager().login());
 
	}
}