当前位置: 首页 > 工具软件 > EWS-Client > 使用案例 >

Java开发 微软OAuth身份验证在EWS中的应用

燕宜修
2023-12-01

一、使用说明

看到有朋友在评论区咨询Java通过Oauth2.0调用EWS的实现。所以有了这篇文章,大概思路是使用Azure的客户端账号和密码通过http方式获取到Token信息,再通过Token去初始化ExchangeService实例,再通过各项API完成各种功能的调用。

二、HTTP方式获取Ews的Token信息

        <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
         <!-- httpclient -->

配置文件

TOKEN_URL=https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/token
TENANT_ID=
CLIENT_ID=
SECRET=
SCOPE=https://outlook.office365.com/.default
GRANT_TYPE=client_credentials

通过http请求方式获取EWS的Token信息

/**
     * 
     * @Description:  使用客户端id密钥获取Ews Token
     * @return
     */
    public static String getEwsTokenWithClientSecret(){
    	
    	 // Load properties file
        Properties properties = new Properties();
        try {
			properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
        String tokenURL = properties.getProperty("TOKEN_URL");
        String tenantId = properties.getProperty("TENANT_ID");
        String clientId = properties.getProperty("CLIENT_ID");
        String clientSecret = properties.getProperty("SECRET");
        String scope = properties.getProperty("SCOPE");
        String grantType = properties.getProperty("GRANT_TYPE");
    	
    	Map<String, String> param = new HashMap<String, String>();
		param.put("tenant", tenantId);
		param.put("client_id", clientId);
		param.put("scope", scope);
		param.put("client_secret", clientSecret);
		param.put("grant_type", grantType);
		
		String result = HttpClientUtil.doPostIgnoreVerifySSL(tokenURL, param);
		System.out.println(result); //这里获取的结果 需要自己把accesstoken字符串自己处理出来
		return result;
    }

我这里的http请求工具类是自己写的忽略了https的证书校验。正式环境建议先导入SSL证书到你的JDK里面。

直接贴代码HttpClientUtil.java文件

package com.zsx.graph.util;

import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/***
 * 通用HttpClientUtil工具类 
 * @author EXT.AZHANG
 *
 */
public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
    
    
    
    /**
     * 
     * @title: doPostJsonIgnoreVerifySSL 
     * @description:	采用绕过验证的方式处理https请求
     * @param url
     * @param json
     * @return 
     * String
     * @throws
     */
    public static String doPostJsonIgnoreVerifySSL(String url, String json) {
    	SSLContext sslcontext = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
        	//设置协议http和https对应的处理socket链接工厂的对象
        	sslcontext = createIgnoreVerifySSL();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);
            //创建自定义的httpclient对象
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
    
    /**
     * 
     * @title: doPostIgnoreVerifySSL 
     * @description:	采用绕过验证的方式处理https请求  模拟表单提交
     * @param url
     * @param param
     * @return 
     */
    public static String doPostIgnoreVerifySSL(String url, Map<String, String> param) {
    	SSLContext sslcontext = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
        	//设置协议http和https对应的处理socket链接工厂的对象
        	sslcontext = createIgnoreVerifySSL();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);
            //创建自定义的httpclient对象
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
}

三、使用token调用ExchangeService

maven依赖,引用如下:

       <!-- Exchange Web Services (EWS) Java API -->
		<dependency>
		  <groupId>com.microsoft.ews-java-api</groupId>
		  <artifactId>ews-java-api</artifactId>
		  <version>2.0</version>
		</dependency>

我这里是查询了指定邮箱Inbox的邮件数量,其他需求请查阅ews的api接口

public static ExchangeService ExchangeService(String token, String mailbox) {
		try {
			ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
			ExchangeCredentials credentials = new WebCredentials();
			service.setCredentials(credentials);
			service.setUrl(new URI("https://outlook.office365.com/ews/exchange.asmx"));
			service.getHttpHeaders().put("Authorization", "Bearer " + token);
			service.setImpersonatedUserId(new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox));
			service.getHttpHeaders().put("X-AnchorMailbox", mailbox);
			return service;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }


public static void main( String[] args ) throws Exception
    {            
        String token = "这里是处理后的token字符串"; 
        String mailbox = "your_mailbox@qq.com";
        ExchangeService service = ExchangeService(token,mailbox);
        Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
		// 获取文件夹里面邮件总数量
		int count = folder.getTotalCount();
		System.out.println(mailbox+" Inbox邮件数量:"+count);
 
    }

冒昧简单整理下发出来供大家参考。后面有时间我再重新优化整理一遍。EWS已经停止支持和安全更新了,建议大家还是转移到Graph上使用。

 类似资料: