Windows User getting “access denied” from exchange

2019-09-14 15:10发布

I have a MVC Web Application makes use of Windows Authentication and Exchange Web Services. While in development, this worked great, since the application pool in IIS on my development machine is set to run under my windows user and the Exchange Server is on the same domain.

On the web server, though, all our applications are set to run under a system user that has access to all the database servers etc. The database connection uses Integrated Security, so I cannot impersonate a user over an application level.

I've been trying to impersonate the current windows user through the code as follows:

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();
    }
}

Then, the class that implements the abstract methods:

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;
    }
}

Then, the methods are accessed as follows:

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);
    }
}

This still works on my local dev machine, but no matter what I do, the user accessing from the server keeps getting an access denied from the exchange server:

The request failed. The remote server returned an error: (401) Unauthorized.

I've tried leaving it on default credentials:

this._service.UseDefaultCredentials = true;

And attempting to manually set the credentials to the current (supposedly impersonated) user:

this._service.Credentials = new WebCredentials(CredentialCache.DefaultNetworkCredentials);

Also, I've tried using the Exchange ImpersonatedUserId object using the email address:

this._service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, from);

which returns the following exception:

The account does not have permission to impersonate the requested user.

2条回答
戒情不戒烟
2楼-- · 2019-09-14 15:13

I tried to change the AD object setting to Trust this computer for delegation.. (you need AD admin rights) but that didn't solve the problem. enter image description here

My breakthrough was to set the Identity of the Application Pool (Advanced Settings...) to NetworkService. It worked also with LocalService and LocalSystem, but be careful because they have elevated rights. What surprised me, that it didn't work with Custom account, when I entered the AD admin account that in reality got all the rights for the exchange system. enter image description here

general infos about my application:

  • ASP.CORE 2.1 webservice
  • Windows Server 2016
  • IIS 10.0.x
  • internal corporate network
查看更多
▲ chillily
3楼-- · 2019-09-14 15:17

By default and as a security measure, Windows will prevent you from delegating your credentials from the web server to Exchange. This means you cannot impersonate the user accessing your web site.

This is known as the "server double hop" scenario. The first "hop" is from the user's machine to the web server, and the second "hop" is from the web server to the Exchange server (Google will give you lots of hits on server double hop).

This is a good thing because it will prevent any hackers from moving around your servers.

The reason it is working on your development machine is that there is only one "hop" from your local web server to the Exchange server.

To solve it you need to allow the web server to delegate the credentials to the Exchange server. This is called Kerberos delegation and must be set up by your system administrator somehow in the Active Directory (which is beyond my knowledge).

查看更多
登录 后发表回答