-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathEWSOAuthHelper.cs
More file actions
73 lines (67 loc) · 3.08 KB
/
EWSOAuthHelper.cs
File metadata and controls
73 lines (67 loc) · 3.08 KB
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
using Microsoft.Exchange.WebServices.Data;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Cache;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Mail2Bug.Email.EWS;
namespace Mail2Bug.Helpers
{
public class EWSOAuthHelper
{
public static ExchangeService OAuthConnectPost(EWSConnectionManger.CredentialsOAuth oAuthCredentials, string emailAddress)
{
string LoginURL = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", oAuthCredentials.TenantID);
var LogValues = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", oAuthCredentials.ClientID },
{ "client_secret", oAuthCredentials.ClientSecret },
{ "scope", "https://outlook.office365.com/.default" }
};
string postData = "";
foreach (var v in LogValues)
{
postData += (String.IsNullOrWhiteSpace(postData) ? "" : "&") + v.Key + "=" + v.Value;
}
var data = Encoding.ASCII.GetBytes(postData);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LoginURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.UserAgent = oAuthCredentials.UserAgentName;
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd();
var aToken = JObject.Parse(json)["access_token"].ToString();
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(aToken);
//Impersonate and include x-anchormailbox headers are required!
ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress);
ewsClient.HttpHeaders.Add("X-AnchorMailbox", emailAddress);
ewsClient.Timeout = 60000;
return ewsClient;
}
}
}
}