Usuário do Windows obtendo "acesso negado" do servidor do Exchange
Eu tenho um aplicativo da Web MVC que usa os serviços da Web de autenticação e Exchange do Windows. Durante o desenvolvimento, isso funcionou muito bem, já que o pool de aplicativos no IIS na minha máquina de desenvolvimento está configurado para ser executado no meu usuário do Windows e o Exchange Server no mesmo domínio.
No servidor da Web, no entanto, todos os nossos aplicativos estão configurados para serem executados em um usuário do sistema que tenha acesso a todos os servidores de banco de dados, etc.
Eu tenho tentado representar o usuário atual do Windows através do código da seguinte maneira:
public abstract class ExchangeServiceImpersonator
{
private static WindowsImpersonationContext _ctx;
public Task<string> CreateMeetingAsync(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
var tcs = new TaskCompletionSource<string>();
EnableImpersonation();
try
{
tcs.TrySetResult(CreateMeetingImpersonated(from, to, subject, body, location, begin, end));
}
catch(Exception e)
{
tcs.TrySetException(e);
}
finally
{
DisableImpersonation();
}
return tcs.Task;
}
public abstract string CreateMeetingImpersonated(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end);
private static void EnableImpersonation()
{
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
_ctx = winId.Impersonate();
}
private static void DisableImpersonation()
{
if (_ctx != null)
_ctx.Undo();
}
}
Em seguida, a classe que implementa os métodos abstratos:
public class ExchangeServiceExtensionsBase : ExchangeServiceImpersonator
{
private ExchangeService _service;
public ExchangeService Service
{
get
{
if (this._service == null)
{
this._service = new ExchangeService(ExchangeVersion.Exchange2013);
this._service.Url = new Uri(WebConfigurationManager.AppSettings["ExchangeServer"]);
this._service.UseDefaultCredentials = true;
}
return this._service;
}
set { return; }
}
public override string CreateMeetingImpersonated(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
//this.Service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, from);
Appointment meeting = new Appointment(Service);
string meetingID = Guid.NewGuid().ToString();
meeting.Subject = subject;
meeting.Body = "<span style=\"font-family:'Century Gothic'\" >" + body.Replace(Environment.NewLine, "<br/>") + "<br/><br/>" +
"<span style=\"color: white;\">Meeting Identifier: " + meetingID + "</span></span><br/><br/>";
meeting.Body.BodyType = BodyType.HTML;
meeting.Start = begin;
meeting.End = end;
meeting.Location = location;
meeting.ReminderMinutesBeforeStart = 60;
foreach (string attendee in to)
{
meeting.RequiredAttendees.Add(attendee);
}
meeting.Save(SendInvitationsMode.SendToAllAndSaveCopy);
return meetingID;
}
}
Em seguida, os métodos são acessados da seguinte maneira:
public static class ExchangeServiceExtensions
{
public static async Task<string> CreateMeetingAsync(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
ExchangeServiceImpersonator serviceImpersonator = new ExchangeServiceExtensionsBase();
return await serviceImpersonator.CreateMeetingAsync(from, to, subject, body, location, begin, end);
}
}
Isso ainda funciona na minha máquina local de desenvolvimento, mas não importa o que eu faça, o usuário acessando do servidor continua recebendo um acesso negado pelo servidor do Exchange:
A solicitação falhou. O servidor remoto retornou um erro: (401) Não autorizado.
Eu tentei deixá-lo em credenciais padrão:
this._service.UseDefaultCredentials = true;
E tentando definir manualmente as credenciais para o usuário atual (supostamente representado):
this._service.Credentials = new WebCredentials(CredentialCache.DefaultNetworkCredentials);
Além disso, tentei usar o ExchangeImpersonatedUserId
objeto usando o endereço de email:
this._service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, from);
que retorna a seguinte exceção:
A conta não tem permissão para representar o usuário solicitado.