java http 客户端使用 kerberos 身份验证将文件上传到共享点

标签 java sharepoint httpclient

需要独立的 Java 程序,以便使用 KERBEROS 身份验证将文件上传到 Sharepoint。

我们有sharepoint服务器,已升级到2010版本并配置了Kerberos身份验证。早期的共享点版本使用 NTLM 身份验证,我有 javaq 客户端程序从本地系统上传文件。由于 sharepoint 通过 Kerberos 身份验证进行了升级,因此我需要修改当前 NTLM 版本的 java 程序以使用 Kerberos。我得到了用于身份验证和连接的代码片段,运行良好。我能够读取 Sharepoint URL 并通过 java 程序下载特定文件。现在我正在尝试将文件上传到 Sharepoint,但没有获得为此所需的 java 类和 jar 文件。

我使用 SPNEGO API 连接共享点进行了 Kerberos 配置设置。

session 文件: krb5.conf 登录.conf

用于 Kerberos 身份验证的 API: spnego-r7.jar

连接性: 以下代码用于连接和文件下载,工作正常。

spnego = new SpnegoHttpURLConnection("spnego-client", <<sharepoint_user>>, <<sharepoint_password>>); 

//New Lines added to omit SSL Handshake exception 
TrustManager[] trustAllCerts = new TrustManager[]{ 
new X509TrustManager() { 
public java.security.cert.X509Certificate[] getAcceptedIssuers(){ 
return null; 
} 
public void checkClientTrusted(java.security.cert.X509Certific ate[] certs, String authType){ 
//No need to implement. 
} 
public void checkServerTrusted(java.security.cert.X509Certific ate[] certs, String authType){ 
//No need to implement. 
} 
} 
}; 
SSLContext sc = SSLContext.getInstance("SSL"); 
sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
HttpsURLConnection.setDefaultSSLSocketFactory(sc.g etSocketFactory()); 
spnego.connect(new URL(spLocation)); 
System.out.println("spnego.getResponseCode():: "+spnego.getResponseCode()); 
if(spnego.getResponseCode() >= 200) { 
log.debug("Authentication Successful"); 
} 

文件读取/下载:

java.io.BufferedInputStream in = new java.io.BufferedInputStream( spnego.getInputStream()); 
java.io.FileOutputStream fos = new java.io.FileOutputStream(outputFile); 
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024); 
byte[] data = new byte[1024]; 
int x=0; 
System.out.println("4" + outputFile.length()); 
while((x=in.read(data,0,1024))>=0) { 
bout.write(data,0,x); 
} 
bout.close(); 
in.close(); 

您能否建议如何使用 java 代码将文件上传到 Sharepoint 文件夹。我在许多论坛中搜索了几个小时,但没有获得文件上传的确切代码。非常感谢您对此的建议。

提前致谢。

最佳答案

经过 10 天的研究和搜索许多博客,我终于找到了问题的解决方案。我希望这可以帮助有需要的人:

将多个文件上传到 SHAREPOINT(经过 KERBEROS 身份验证):

    System.setProperty("java.security.krb5.conf", workareaFolder+"/"+props.getProperty("kerberos.conf.file"));
    System.setProperty( "java.security.auth.login.config", workareaFolder+"/"+props.getProperty("jass.conf.file"));
    System.setProperty( "javax.security.auth.useSubjectCredsOnly", "false");           

    krb5MechOid    = new Oid("1.2.840.113554.1.2.2");
    spnegoMechOid  = new Oid("1.3.6.1.5.5.2");

      shost= targetSPN.toLowerCase();
      if (shost.startsWith("http/") || shost.startsWith("cifs/") )  {
          shost = shost.substring(5);
      }  
      else  {
          log.debug("Entered invalid SPN.  Must begin with HTTP/ or CIFS/");
          System.exit(-1);
      }
      this.checkSPNHostname(shost);                     

    //login to the KDC using JAAS login module
    this.subject = login(username, password);

    log.debug(this.subject);

    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                        return null;
                }
                public void checkClientTrusted(X509Certificate[] certs,
                                String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs,
                                String authType) {
                }
    } }, new SecureRandom());

    Scheme httpScheme80 = new  Scheme("http", 80,  PlainSocketFactory.getSocketFactory());
    SSLSocketFactory sf = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new  Scheme("https", 443, sf);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    schemeRegistry.register(httpScheme80);

    // Create Connection Manager instance for use by Httpclient
    cm = new SingleClientConnManager(schemeRegistry);
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    httpclient = new DefaultHttpClient(cm,params);
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy());

    File[] listOfFiles = folder.listFiles(new FileFilter() {
                                                public boolean accept(File f) {
                                                    if (f.isFile()) {
                                                        return true;
                                                    }
                                                    return false;
                                                }
                                            });
    String[] url = new String[listOfFiles.length];
    String spTargetFolder = new String();

    totalFilesInReportsFolder = listOfFiles.length;

    for (int i = 0; i < totalFilesInReportsFolder; i++) {
        uploadFileName = listOfFiles[i].getName();
        log.info("\nFile: "+uploadFileName);

        spTargetFolder = this.getSPFolder(uploadFileName);
        spDestinationFolderURL = sharedDocumentsRoot + instanceFolder + "/" + spTargetFolder + "/" + uploadFileName;
        //log.info("Destination URL : " + spDestinationFolderURL);

        httpPut = new HttpPut(new URI(sharedDocumentsRoot + instanceFolder + "/" + spTargetFolder + "/" + uploadFileName));
        httpPut.getParams().setParameter("http.protocol.handle-redirects",true);
        InputStreamEntity inputStreamEntity = new InputStreamEntity(new FileInputStream(listOfFiles[i]), listOfFiles[i].length());
        httpPut.setEntity(inputStreamEntity);
        // Get the service ticket for targetSPN and set it in HttpPut Authorization header
        this.serviceTicket= initiateSecurityContext( targetSPN );
        encodedBytes  = org.apache.commons.codec.binary.Base64.encodeBase64(this.serviceTicket);
        encoded =   new String(encodedBytes);
        httpPut.addHeader("Authorization", "Negotiate " + encoded);

        httpResponse = null;

        try {
             log.info("Uploading File... ");
             log.debug("Executing httpPut request: " + httpPut.getRequestLine());           
             httpResponse = httpclient.execute(httpPut);
             log.debug("After Post - Status code:" +httpResponse.getStatusLine().getStatusCode());
             BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
             StringBuilder s = new StringBuilder();
             String sResponse; 
             while ((sResponse = reader.readLine()) != null) {
                 s = s.append(sResponse);
             }


             if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                 log.info("Response Code received: "+ httpResponse.getStatusLine() +" [200 - CREATE / OVERWRITE]");
                 log.info("File Sucessfully uploaded to Sharepoint location: "+spDestinationFolderURL );
                 uploadSuccessCount++;
             } else {
                 log.error("Error while uploading file to sharepoint");
                 if (httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED){
                     log.error("Response code: "+httpResponse.getStatusLine().getStatusCode());
                     log.error("Response Text:" + s);
                 }
                 uploadFailCount++;
             }

             log.debug("----------------------------------------");
             log.debug("Response StatusLine: "+ httpResponse.getStatusLine());
             log.debug("----------------------------------------");
             log.debug("Return Code : " + httpResponse.getStatusLine().getStatusCode());
             log.debug("----------------------------------------");

        } catch (Exception exp) {
            log.error("Exception while uploading report \""+uploadFileName+"\" to Share point="+exp);
            exp.printStackTrace();
        }
    }

关于java http 客户端使用 kerberos 身份验证将文件上传到共享点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746659/

相关文章:

java - 使用 getWritableDatabase() 时需要调用 close() 吗?

java - 我在 java rmi 多客户端代码中遇到问题

java - 在大数据(数千行和列)的情况下,为每个单元格设置 CellStyle() 会花费很长时间

sharepoint - 如何通过 SSL 启用 SharePoint

java - RESTEasy - 如何为 ClientRequest 设置基本身份验证

android - 使用 httpPost 和 httpclient 保存 cookie

c# - HTTP PATCH 方法 C#

java - HashMap 映射值略有偏差

Sharepoint XSL 数据 View 查询字符串过滤

c# - 在不使用 Web 服务的情况下以编程方式从 Sharepoint 下载文件?