Skip to content

Instantly share code, notes, and snippets.

@mirontoli
Created September 11, 2012 23:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mirontoli/3702971 to your computer and use it in GitHub Desktop.
Save mirontoli/3702971 to your computer and use it in GitHub Desktop.
SharePoint Online Java Login
package spauth;
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 login = "/_forms/default.aspx?wa=wsignin1.0";
// SAML.xml from https://github.com/lstak/node-sharepoint
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]", "something@something.onmicrosoft.com");
saml = saml.replace("[password]", "p@ssw0rd");
saml = saml.replace("[endpoint]", "http://something.sharepoint.com");
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("POST");
// 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.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 {
//http://stackoverflow.com/questions/773012/getting-xml-node-text-value-with-java-dom
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());
//handle error S:Fault:
//http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/df862099-d9a1-40a4-b92e-a107af5d4ca2
System.out.println(token);
return token;
}
private String submitToken(String token) throws IOException {
//String token = "t=EwBwAk6hBwAUIQT64YiMbkZQLHdw6peopUrQ0O8AAYkt43mh328r0OTpTqSVMQEWGlzlpE906mSyOfU2JgkHQCBz0VBLPKyFEYeCUUqLQ0FmodljevOEceo5L1r+aj207XYvgGl+QBOMxSuNtdbPprICB/+NhRxEynCQe2l1U84a3S20At+OsGorLHKpp1RIfjR6FGGW3ahltWwDvvkcLY5mMtvOHoQx+citNFIvXGY4zzosNgum0OXMlIz26QfODI705ICMV9wmLfbJ4xQjeRAHFrPQxdeQ3mA9tepV9zPKyeAsAmFrMb0/3GUh9GK0jk9O1+N5PZYtL4cKsOrMbGN3Z++IhoTrwLR6/8PJrZNtyKJhv/W35N66THKsKH0DZgAACDKSCSEEFKnaQAEQ+c2vlhFUJ1WBjs9puwnuOFye+J6AvcpFrCaefpBozSYZTQAwJDuHu51xUyrUhrPetgTekrM04m7q6IpqccJBFxTzd3UAkJLgFJQpcerLOFKgYMrVNWOyqEPzn9Zdjv3Xa73HGa36kOUqZeDPcBcxOtMy0I5LmV8tQ4a3Cc302hDax208/eL1fi5xqEiUE89DLEJ8w9KyIWfVUFwvs3r374t/7KJmQH55yZk3p874gNFyToHA4s+0ZuMikRyDTXeYPQ/Jz8rgIYGA+dCwDNb6x+2y26TRX9QiWYvuhcJ8V1xola+Wo6tjHJwon+8QHXLjCiOXkLUvZbjnR2X+UoAnAYNYb5YVeTBqQSO2l19VhK4o5tnHvOhnwVBM8DeGFJSeMChqS7SlPzq/39ntZtPmv9HuvFrP8801pW9KmxgXdoEB&p=";
// http://cafeconleche.org/books/xmljava/chapters/ch03s05.html
String url = "http://something.sharepoint.com" + login;
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() +
// "");
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;
}
}
<?xml version="1.0" encoding="utf-8" ?>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<S:Header>
<wsa:Action xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Action" S:mustUnderstand="1">
http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue
</wsa:Action>
<wsa:To xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="To" S:mustUnderstand="1">
http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
</wsa:To>
<wsse:Security S:mustUnderstand="1">
<wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="TS">
<wsu:Created>2012-09-12T14:57:18Z</wsu:Created>
<wsu:Expires>2012-09-12T15:02:18Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</S:Header>
<S:Body>
<wst:RequestSecurityTokenResponse xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault">
<wst:TokenType>urn:passport:compact</wst:TokenType>
<wsp:AppliesTo xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:EndpointReference>
<wsa:Address>http://takana.sharepoint.com/_forms/default.aspx?wa=wsignin1.0
</wsa:Address>
</wsa:EndpointReference>
</wsp:AppliesTo>
<wst:Lifetime>
<wsu:Created>2012-09-12T14:57:18Z</wsu:Created>
<wsu:Expires>2012-09-13T14:57:18Z</wsu:Expires>
</wst:Lifetime>
<wst:RequestedSecurityToken>
<wsse:BinarySecurityToken Id="Compact0">t=EwBwAk6hBwAUIQT64YiMbkZQLHdw6peopUrQ0O8AAWu99/2l9hPHfHjLLPIKlALPAv9uEAx/eGWdGQ5/C263c9i4TdOpOe15TWChlW6800MN6txONjG6jXOXQmnN7bs+LF8fgGyhehbZS4cPtF8amhc90izMlMQyf2wAbTy8arLdhNmUro1QZmWVkUc34kaM5bygYTzvNk7dhYKwwZDsBeOPElptD4CHoeoayMr1/+kwDamUoU3mdQEuksdllM+SCiqFG7AXJ6sA1WMMDCvSNLQAtTPYdoKcmwWQui3Qqi+YILI9v8vf589t44YF1HW/lgr49dxgtd2qEMI9x00icOpkralYn835P4mTY7SVNlB2IFQjEW/V3ouRp121zp8DZgAACB3BBYFwGFPOQAFv9sRafvPptNXwQxzlbkRt9Mxe8ehqzd9PTZGu9HZpbFn0BPyV5enMuwdOGAKJrWa3lo5+v0OsNonNqInqMiXiiyQS1vF4HNT4VA4CmcK454seuWxjIh8b2CmMKQSItngcZ6IT+c5mrwT472S2Ed4yg6hK237oqpUjA+PNo3KCIn5/Mg3XwBszYIorwikUHjJg9bHfADtPWERccjB+cCocGUuiMPzL7iUZvQzRpa5qzVVWt06MLcL3FJ88KBZ45jtfgehDc3H8/TnwObSjvmhgR2lHh7V9wrg98/K7M7tNSx8eBAOWfRDe5MBjjPtXKQBiUhYVVXen/YqA4aOiEnx2YwCjgxBTkQK7Vhaj78BMMhoq3nEyy6FLmHjUzAYOxugFS3y9WCkp7iKy/GpiMQrNeyGvdlmKH6rAsuWD8WTx6oEB&amp;p=</wsse:BinarySecurityToken>
</wst:RequestedSecurityToken>
<wst:RequestedAttachedReference>
<wsse:SecurityTokenReference>
<wsse:Reference URI="f7fmapTZOXJWT326j30BtN4jMDU="></wsse:Reference>
</wsse:SecurityTokenReference>
</wst:RequestedAttachedReference>
<wst:RequestedUnattachedReference>
<wsse:SecurityTokenReference>
<wsse:Reference URI="f7fmapTZOXJWT326j30BtN4jMDU="></wsse:Reference>
</wsse:SecurityTokenReference>
</wst:RequestedUnattachedReference>
</wst:RequestSecurityTokenResponse>
</S:Body>
</S:Envelope>
@waleedmashaqbeh
Copy link

Thnx for your code however I have test the above code on sharepoitn online 2013 and it gives me the folowing error

S:Sender/S:Valuewst:InvalidRequest/S:Value/S:Subcode/S:CodeInvalid Request/S:Text/S:Reasonpsf:errorpsf:value0x80048820/psf:valuepsf:internalerrorpsf:code0x80045c01/psf:codepsf:textInvalid STS request. /psf:text/psf:internalerror/psf:error/S:Detail/S:Fault/S:Body/S:Envelope

@poojagaonkar19
Copy link

Hi,
I have followed you code and everything seems good. The only problem is that I get an 403 forbidden message while logging in and am unable to fetch the cookies

@nddipiazza
Copy link

403 error as well. doesn't work.

@nddipiazza
Copy link

@love2210
Copy link

love2210 commented Nov 4, 2018

Hello, I can get Token and FedAuth and rtFa cookie .
But I want to use those data to login my sharepoint site page(https://teaner.sharepoint.com/site/mysite)on browser.
How to do it?
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment