Question

I find it very strange that I am able to create appointments in my calendar on our company's exchange 2010 server using the asp.net 4.0 web application running on my XP machine which is not even part of the domain!, BUT when I upload the same code to our company's production Web application server (which is not same as the Exchange server), then I get the error as follows:

System.Net.WebException: The remote server returned an error: (401) Unauthorized

I am using Window's authentication throughout. Using service.UseDefaultCredentials = true; I just cannot afford to use the username/paasword for every staff who will be using this application. I am thinking there is some problem (rights/permissions/disabled impersonation) issue at the production Web application server (Windows 2008 m/c). I even played with the Application pool identity in IIS 7 by selecting all the builtin accounts it can possibly run under, but same error. I can clearly see that it is running under my Windows account right before the Appointment.Save() call is made. I am briefly impersonating using the logged in user's credentials and then removing the impersonation. I saw this technique elsewhere. But that doesn't make any difference either.

These are the code files:

Default.aspx.cs

//(nothing much is going on in the markup page Default.aspx. Therefore not including)

            using System;
            using System.Collections.Generic;
            using System.Web;
            using System.Web.UI;
            using System.Web.UI.WebControls;


            using  Microsoft.Exchange.WebServices.Data;
            using Microsoft.Exchange.WebServices.Autodiscover;
            using System.Web.Configuration;

            namespace TestExchangeWebServices
            {
                public partial class _Default : System.Web.UI.Page
                {
                    protected ExchangeService service;

                    protected void Page_Load(object sender, EventArgs e)
                    {
                        service = new ExchangeService(ExchangeVersion.Exchange2010);
                        service.UseDefaultCredentials = true;
                        service.Url = new Uri(WebConfigurationManager.AppSettings["EWSURL"]);


                        SetAppointment("Test", DateTime.Now, "Test");

                    }

                    public void SetAppointment(string Subject, DateTime AptDateTime, string Body)
                    {
                        Appointment apt = new Appointment(service);
                        apt.Subject = Subject;
                        apt.Body = Body;
                        apt.Body.BodyType = BodyType.HTML;
                        apt.Start = AptDateTime;
                        apt.End = apt.Start.AddMinutes(30.00);
                        apt.ReminderMinutesBeforeStart = 15;
                        apt.IsReminderSet = true;

                        HttpContext.Current.Trace.Write("Before Impersonation: System.Security.Principal.WindowsIdentity.GetCurrent().Name = " + System.Security.Principal.WindowsIdentity.GetCurrent().Name  );

                        System.Security.Principal.WindowsImpersonationContext impersonationContext;
                        impersonationContext = ((System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();// //System.Threading.Thread.CurrentPrincipal.Identity

                        HttpContext.Current.Trace.Write("Before Saving Appointment. System.Security.Principal.WindowsIdentity.GetCurrent().Name = " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
//This is where the call is made and error occurs                            
apt.Save(SendInvitationsMode.SendToNone);
                        HttpContext.Current.Trace.Write("After Saving Appointment.");

                        impersonationContext.Undo();
                    }

                }
            }

Web.Config

  <?xml version="1.0"?>


  <configuration>
    <appSettings configProtectionProvider="RsaProtectedConfigurationProvider">
      <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
        xmlns="http://www.w3.org/2001/04/xmlenc#">
        <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
          <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
            <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
              <KeyName>Rsa Key</KeyName>
            </KeyInfo>
            <CipherData>
              <CipherValue>0Sw7QiYFKoD65nCXfakXUhJrjapk4uyQ9u6aPBStxB1XBIIPtXbuZJZb/GyMxgl7Gi3sqIkoq66BKa+MSzjAkpkIfnZmOhMNVomKofC3rlEf9NeIAdCEvjcmENhfGyA6aEJj96mGDxRDBE/FP1iQ8Z3x8Rob+HG1sbD0YJy2rpA=</CipherValue>
            </CipherData>
          </EncryptedKey>
        </KeyInfo>
        <CipherData>
          <CipherValue>HmmlAzyuedvlQ/+grwRKjTs5Z7sg5dYShHFYsFcI0q2ugkZ7oYYNTTEycyqzKyXmaaqwyE2lAsApApSvT+JDys021+sMrqLrF37xAkjRimKbPTylgznRZLQx2qKAZstb6qIis2mcLykgURtp2ytfoPl83jJzEU1y6PtB0loB/p4=</CipherValue>
        </CipherData>
      </EncryptedData>
    </appSettings>
    <connectionStrings>
      <add name="ApplicationServices"
           connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
           providerName="System.Data.SqlClient" />
    </connectionStrings>

    <system.web>
      <identity impersonate="false"/>

      <customErrors mode="Off"></customErrors>

      <compilation debug="true" targetFramework="4.0" />

      <authentication mode="Windows">

      </authentication>

      <membership>
        <providers>
          <clear/>
          <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
               enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
               maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
               applicationName="/" />
        </providers>
      </membership>

      <profile>
        <providers>
          <clear/>
          <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
        </providers>
      </profile>

      <roleManager enabled="false">
        <providers>
          <clear/>
          <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
          <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
        </providers>
      </roleManager>

    </system.web>

    <system.webServer>
       <modules runAllManagedModulesForAllRequests="true"/>

       <httpErrors errorMode="Detailed" />
       <asp scriptErrorSentToBrowser="true"/>

    </system.webServer>
  </configuration>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top