I wanted to use the EWS Managed API in my Office Mail App. I would like to obtain the credential from the mailbox in JS and then pass it to the code behind to create the Microsoft.Exchange.WebServices.Data.ExchangeService object. I was able to create the object if I use the WebCredential with username and password, but I would like to use the credential in the mailbox, so I don't have to ask the user for username and password again. I saw that there is an identitytoken available in JS
Office.initialize = function () {
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
_mailbox = Office.context.mailbox;
_mailbox.getUserIdentityTokenAsync(getUserIdentityTokenCallback);
_Item = _mailbox.item;
$(mailID).val(_Item.itemId);
$(url).val(_mailbox.ewsUrl);
});
}
function getUserIdentityTokenCallback(asyncResult) {
$(token).val(asyncResult.value);
}
so, I tried to use this token to create the ExchangeService object and get the mail item like below.
public Item Test(string email, string token, string mailID, string url)
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exchangeService.Credentials = new TokenCredentials(token);
exchangeService.TraceEnabled = true;
exchangeService.TraceFlags = TraceFlags.All;
exchangeService.Url = new Uri(url);
Item item = null;
try
{
item = this.GetEmail(mailID);
}
catch (Exception ex)
{
string a;
}
return item;
}
public Item GetEmail(string mailID)
{
if (!string.IsNullOrEmpty(mailID))
{
Logger.ErrorLog("GetEmail: mailID =" + mailID);
ItemId itemID = new ItemId(mailID);
Item emailItem = Item.Bind(exchangeService, itemID);
emailItem.Load(new PropertySet(Exchange.BasePropertySet.FirstClassProperties, ItemSchema.MimeContent));
return emailItem;
}
else
{
throw new Exception("mailID is null or empty");
}
}
I get the following exception:
{
"The request failed. The remote server returned an error: (401) Unauthorized."}
on Item emailItem = Item.Bind(exchangeService, itemID); in the GetEmail function. How do I properly retrieve tokens in JS in the mailbox to create a EWS Managed API ExchangeServices?
Thank, Hilda
- Edited by hlee Thursday, March 06, 2014 7:23 AM


