Oana Marina
Oana Marina

Reputation: 289

Exchange Server - Unauthorized

We have an MVC app that connects to the Exchange server. We used to connect to an on premises server using this code to create the service:

if (string.IsNullOrEmpty(Current.UserPassword))
        {
            throw new UnauthorizedAccessException("Exchange access requires Authentication by Password");
        }
        return new ExchangeService
            {
                Credentials = new NetworkCredential(Current.User.LoginName, Current.UserPassword),
                Url = new Uri(ConfigurationManager.AppSettings["ExchangeServiceUrl"]),
            };

This worked fine, but now our IT department is migrating the Exchange server to the cloud, and some users are on the cloud server while others are on premises. So I changed the code to this:

if (string.IsNullOrEmpty(Current.UserPassword))
        {
            throw new UnauthorizedAccessException("Exchange access requires Authentication by Password");
        }
        var user = ConfigurationManager.AppSettings["ExchangeUser"];
        var password = ConfigurationManager.AppSettings["ExchangePassword"];
        var exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
        {
            Credentials = new NetworkCredential(user, password),
        };
        exchangeService.AutodiscoverUrl(Current.EmaiLuser + "@calamos.com", RedirectionCallback);
        exchangeService.Credentials = new NetworkCredential(Current.EmaiLuser + "@calamos.com", Current.UserPassword);
        return exchangeService;

I am using a service account to do the autodiscovery ( for some reason it doesn't work with a regular account) and then I am changing the credentials of the service to the user that logs in, so he can access the inbox. The problem is that , randomly, the server returns "The request failed. The remote server returned an error: (401) Unauthorized.". I asked the IT department to check the Exchange logs, but there is nothing there about this error, so I don't know how to fix it...

Upvotes: 0

Views: 245

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

So by cloud do you mean Office365 ?

I am using a service account to do the autodiscovery ( for some reason it doesn't work with a regular account)

For the users in the cloud you need to ensure the request are sent to the cloud servers maybe enable tracing https://msdn.microsoft.com/en-us/library/office/dd633676(v=exchg.80).aspx and then have a look at where the failed requests are being routed. From what you are saying your discovery is going to always point to your internal servers which is why the request will fail for the cloud based users. You need to have a way of identifying the users that are in the cloud and I would suggest you then just use the single Office365 Endpoint (eg you don't need Autodiscover for that) https//outlook.office365.com/EWS/Exchange.asmx

Upvotes: 1

Related Questions