The remote server returned 401 unauthorized ошибка

Появление сообщения об ошибке 401 Unauthorized Error («отказ в доступе») при открытии страницы сайта означает неверную авторизацию или аутентификацию пользователя на стороне сервера при обращении к определенному url-адресу. Чаще всего она возникает при ошибочном вводе имени и/или пароля посетителем ресурса при входе в свой аккаунт. Другой причиной являются неправильные настройки, допущенные при администрировании web-ресурса. Данная ошибка отображается в браузере в виде отдельной страницы с соответствующим описанием. Некоторые разработчики интернет-ресурсов, в особенности крупных порталов, вводят собственную дополнительную кодировку данного сбоя:

  • 401 Unauthorized;
  • Authorization Required;
  • HTTP Error 401 – Ошибка авторизации.

Попробуем разобраться с наиболее распространенными причинами возникновения данной ошибки кода HTTP-соединения и обсудим способы их решения.

Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя

При доступе к некоторым сайтам (или отдельным страницам этих сайтов), посетитель должен пройти определенные этапы получения прав:

  1. Идентификация – получение вашей учетной записи («identity») по username/login или email.
  2. Аутентификация («authentic») – проверка того, что вы знаете пароль от этой учетной записи.
  3. Авторизация – проверка вашей роли (статуса) в системе и решение о предоставлении доступа к запрошенной странице или ресурсу на определенных условиях.

Большинство пользователей сохраняют свои данные по умолчанию в истории браузеров, что позволяет быстро идентифицироваться на наиболее часто посещаемых страницах и синхронизировать настройки между устройствами. Данный способ удобен для серфинга в интернете, но может привести к проблемам с безопасностью доступа к конфиденциальной информации. При наличии большого количества авторизованных регистрационных данных к различным сайтам используйте надежный мастер-пароль, который закрывает доступ к сохраненной в браузере информации.

Наиболее распространенной причиной появления ошибки с кодом 401 для рядового пользователя является ввод неверных данных при посещении определенного ресурса. В этом и других случаях нужно попробовать сделать следующее:

  1. Проверьте в адресной строке правильность написания URL. Особенно это касается перехода на подстраницы сайта, требующие авторизации. Введите правильный адрес. Если переход на страницу осуществлялся после входа в аккаунт, разлогинитесь, вернитесь на главную страницу и произведите повторный вход с правильными учетными данными.
  2. При осуществлении входа с сохраненными данными пользователя и появлении ошибки сервера 401 проверьте их корректность в соответствующих настройках данного браузера. Возможно, авторизационные данные были вами изменены в другом браузере. Также можно очистить кэш, удалить cookies и повторить попытку входа. При удалении истории браузера или очистке кэша потребуется ручное введение логина и пароля для получения доступа. Если вы не помните пароль, пройдите процедуру восстановления, следуя инструкциям.
  3. Если вы считаете, что вводите правильные регистрационные данные, но не можете получить доступ к сайту, обратитесь к администратору ресурса. В этом случае лучше всего сделать скриншот проблемной страницы.
  4. Иногда блокировка происходит на стороне провайдера, что тоже приводит к отказу в доступе и появлению сообщения с кодировкой 401. Для проверки можно попробовать авторизоваться на том же ресурсе с альтернативного ip-адреса (например, используя VPN). При подтверждении блокировки трафика свяжитесь с провайдером и следуйте его инструкциям.

Некоторые крупные интернет-ресурсы с большим количеством подписчиков используют дополнительные настройки для обеспечения безопасности доступа. К примеру, ваш аккаунт может быть заблокирован при многократных попытках неудачной авторизации. Слишком частые попытки законнектиться могут быть восприняты как действия бота. В этом случае вы увидите соответствующее сообщение, но можете быть просто переадресованы на страницу с кодом 401. Свяжитесь с администратором сайта и решите проблему.

Иногда простая перезагрузка проблемной страницы, выход из текущей сессии или использование другого веб-браузера полностью решают проблему с 401 ошибкой авторизации.

Ошибка 401 - отказ в доступе

Устранение ошибки 401 администратором веб-ресурса 

Для владельцев сайтов, столкнувшихся с появлением ошибки отказа доступа 401, решить ее порою намного сложнее, чем обычному посетителю ресурса. Есть несколько рекомендаций, которые помогут в этом:

  • Обращение в службу поддержки хостинга сайта. Как и в случае возникновения проблем с провайдером, лучше всего подробно описать последовательность действий, приведших к появлению ошибки 401, приложить скриншот.
  • При отсутствии проблем на стороне хостинг-провайдера можно внести следующие изменения в настройки сайта с помощью строки Disallow:/адрес проблемной страницы. Запретить индексацию страницам с ошибкой в «rоbоts.txt», после чего добавить в файл «.htассеss» строку такого типа:
Redirect 301 /oldpage.html http://site.com/newpage.html.

Где в поле /oldpage.html прописывается адрес проблемной страницы, а в http://site.com/newpage.html адрес страницы авторизации.

Таким образом вы перенаправите пользователей со всех страниц, которые выдают ошибку 401, на страницу начальной авторизации.

  • Если после выполнения предыдущих рекомендаций пользователи при попытках авторизации все равно видят ошибку 401, то найдите на сервере файл «php.ini» и увеличьте время жизни сессии, изменив значения следующих параметров: «session.gc_maxlifetime» и «session.cookie_lifetime» на 1440 и 0 соответственно.
  • Разработчики веб-ресурсов могут использовать более сложные методы авторизации и аутентификации доступа для создания дополнительной защиты по протоколу HTTP. Если устранить сбой простыми методами администрирования не удается, следует обратиться к специалистам, создававшим сайт, для внесения соответствующих изменений в код.

Хотя ошибка 401 и является проблемой на стороне клиента, ошибка пользователя на стороне сервера может привести к ложному требованию входа в систему. К примеру, сетевой администратор разрешит аутентификацию входа в систему всем пользователям, даже если это не требуется. В таком случае сообщение о несанкционированном доступе будет отображаться для всех, кто посещает сайт. Баг устраняется внесением соответствующих изменений в настройки.

Дополнительная информация об ошибке с кодом 401

Веб-серверы под управлением Microsoft IIS могут предоставить дополнительные данные об ошибке 401 Unauthorized в виде второго ряда цифр:

  • 401, 1 – войти не удалось;
  • 401, 2 – ошибка входа в систему из-за конфигурации сервера;
  • 401, 3 – несанкционированный доступ из-за ACL на ресурс;
  • 401, 501 – доступ запрещен: слишком много запросов с одного и того же клиентского IP; ограничение динамического IP-адреса – достигнут предел одновременных запросов и т.д.

Более подробную информацию об ошибке сервера 401 при использовании обычной проверки подлинности для подключения к веб-узлу, который размещен в службе MS IIS, смотрите здесь. 

Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке:

  • 400 Bad Request; 
  • 403 Forbidden; 
  • 404 Not Found;
  • 408 Request Timeout.

Как видим, появление ошибки авторизации 401 Unauthorized не является критичным для рядового посетителя сайта и чаще всего устраняется самыми простыми способами. В более сложной ситуации оказываются администраторы и владельцы интернет-ресурсов, но и они в 100% случаев разберутся с данным багом путем изменения настроек или корректировки html-кода с привлечением разработчика сайта. 

I’ll let you have a piece of code I made that is working. I also had the 401 Auth issue, that was while back and I don’t remember what I exactly modified to make it work, but it does now. Of course you don’t need the whole code but it gives you an idea.

public class Outlook
{
    /// <summary>
    /// Returns the selected node Index which equals selected mail index.
    /// </summary>
    public static Int32 selectedMailindex
    {
        get
        {
            return (Int32)Form1.GlobalAccess.Invoke((Func<int>)delegate
            {
                return Form1.GlobalAccess.mailTree.SelectedNode.Index;
            }); 
        }
    }

    static PullSubscription subscriptionInbox;
    public static ExchangeService runningService;

    /// <summary>
    /// Used to save EmailMessage retrieved from user inbox.
    /// </summary>
    public static List<EmailMessage> mailMessages = new List<EmailMessage>();

    /// <summary>
    /// We start the procedure to grab Emails.
    /// </summary>
    public static void StartupLoadMails()
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        service.TraceEnabled = true;
        service.Credentials = new WebCredentials("username", "password"); //Modify this
        service.Url = new Uri("Exchange.asmx URL"); //Modify this
        GetBinding(service);
        runningService = service;
        GetMailItems(runningService);
    }

    static ExchangeService GetBinding(ExchangeService service)
    {
        //Subscribe to Inbox newmail/modified events.
        subscriptionInbox = service.SubscribeToPullNotifications(
        new FolderId[] { WellKnownFolderName.Inbox }, //Inbox
        5, //TimeOut
        null,
        EventType.NewMail, EventType.Modified); //NewMail or Modified
        // Display the service URL.
        return service;
    }

    /*static bool RedirectionUrlValidationCallback(String redirectionUrl)
    {
        return true;
    }*/

    public static void GetMailItems(ExchangeService service)
    {
        Form1.GlobalAccess.Invoke(new Action(() =>
        {
            Form1.GlobalAccess.mailTree.Nodes.Clear();                
        }));
        mailMessages.Clear();
        //SearchFilter to get unreaded messages only.
        SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
        //Create new Item view with the last 9 unreaded items.
        ItemView view = new ItemView(9);
        //Execute the query
        FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
        //We use Parallel for faster initial app loading, reducing ~5/10 secs.
        Parallel.ForEach(findResults, item =>
            {
                try
                {
                    EmailMessage message = EmailMessage.Bind(service, item.Id);
                    mailMessages.Add(message);
                }
                catch
                {
                    MessageBox.Show("ERROR");
                }
            });

        //Since we used parallel we need to sort the emails in our EmailMessage LIST by date, so they show cronologicaly over the treeview.
        mailMessages.Sort(delegate(EmailMessage m1, EmailMessage m2) { return m2.DateTimeReceived.Date.CompareTo(m1.DateTimeReceived.Date); });
        foreach (EmailMessage m in mailMessages)
        {
            Form1.GlobalAccess.Invoke(new Action(() =>
            {
                Form1.GlobalAccess.mailTree.Nodes.Add(m.Subject + " : " + m.Sender.Name);
            }));
        }
    }

    /// <summary>
    /// Calls threaded MarkReaded function to mark an Email as readed localy and remotly.
    /// </summary>
    public static void MarkReaded()
    {
        Thread thread = new Thread(CallThreadedReadFunction);
        thread.Priority = ThreadPriority.AboveNormal;
        thread.Start();
    }

    static void CallThreadedReadFunction()
    {
        ReadFunction(Outlook.mailMessages[selectedMailindex],selectedMailindex,runningService);
    }

    /// <summary>
    /// Mark as readed
    /// </summary>
    /// <param name="message">E-mail Message</param>
    /// <param name="index">Index Message Possition</param>
    /// <param name="service">EWS Service</param>
    static void ReadFunction(EmailMessage message, Int32 index, ExchangeService service)
    {
        Form1.GlobalAccess.Invoke(new Action(() =>
        {
            Form1.GlobalAccess.mailTree.Nodes[index].SelectedImageIndex = 3;
            Form1.GlobalAccess.mailTree.Nodes[index].ImageIndex = 3;
        }));
        EmailMessage msg = EmailMessage.Bind(service, message.Id);
        msg.IsRead = true;
        msg.Update(ConflictResolutionMode.AutoResolve);
    }

    /// <summary>
    /// Calls threaded Delete function to delete an Email localy and remotly.
    /// </summary>
    public static void Delete()
    {
        var deleteWorker = new BackgroundWorker();

        deleteWorker.DoWork += (sender, args) =>
        {
            DeleteFunction(Outlook.mailMessages[selectedMailindex], selectedMailindex, runningService);
        };

        deleteWorker.RunWorkerCompleted += (sender, args) =>
        {
            if (args.Error != null)
                MessageBox.Show(args.Error.ToString());

            Form1.GlobalAccess.Invoke(new Action(() =>
            {
                Form1.GlobalAccess.mailrefreshIcon.Visible = true;
            }));
        };

        deleteWorker.RunWorkerAsync();
    }

    /// <summary>
    /// Delete Emails choosen by the user.
    /// </summary>
    /// <param name="message">E-mail Message</param>
    /// <param name="index">Index Message Possition</param>
    /// <param name="service">EWS Service</param>
    public static void DeleteFunction(EmailMessage message, Int32 index, ExchangeService service)
    {
        try
        {
            Form1.GlobalAccess.Invoke(new Action(() =>
            {
                Form1.GlobalAccess.mailTree.Nodes.RemoveAt(index);
                mailMessages.RemoveAt(index);
                Form1.GlobalAccess.mailTree.SelectedNode = null;
                Form1.GlobalAccess.mailBrowser.DocumentText = null;
            }));

            EmailMessage msg = EmailMessage.Bind(service, message.Id);
            msg.Delete(DeleteMode.MoveToDeletedItems);
            msg.Update(ConflictResolutionMode.AlwaysOverwrite);
        }
        catch
        {
            //En ocaciones, si se borran muchos emails consecutivamente y se da refresh al inbox rapidamente, causa un crash porque el servidor encuentra el email que ordenamos borrar y mientras esta
            //Iterando es borrado, causando un crash. Lo mejor es unicamente ignorar la excepción, el programa seguira trabajando bien.
        }
    }

    /// <summary>
    /// Listens for new mails in the user inbox folder, if found, notifies the user and update mail list.
    /// </summary>
    /// <param name="service">EWS Service</param>
    public static void GetLatests(ExchangeService service)
    {
        GetEventsResults eventsInbox = subscriptionInbox.GetEvents();
        EmailMessage message;
        // Loop through all item-related events.
        foreach (ItemEvent itemEvent in eventsInbox.ItemEvents)
        {
            switch (itemEvent.EventType)
            {
                case EventType.NewMail:
                    try
                    {
                        Item item = Item.Bind(service, itemEvent.ItemId);
                        if (item.ItemClass.ToLower() == "IPM.Note".ToLower())
                        {
                            message = EmailMessage.Bind(service, itemEvent.ItemId);
                                Form1.GlobalAccess.Invoke(new Action(() =>
                                {
                                if (Form1.GlobalAccess.mailTree.Nodes.Count == 8)
                                {
                                    try
                                    {
                                        Form1.GlobalAccess.mailTree.Nodes.RemoveAt(8);
                                        mailMessages.RemoveAt(8);
                                    }
                                    catch
                                    {
                                    }
                                }
                                Form1.GlobalAccess.mailTree.Nodes.Insert(0, message.Subject);
                                mailMessages.Insert(0, message);
                                }));
                            }               
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
            }
        }
    }

    /// <summary>
    /// Reply to a single user. This method gets called from ReplyMail winform.
    /// </summary>
    /// <param name="message">Email Message OBJECT</param>
    /// <param name="index">Email position in the tree</param>
    /// <param name="service">EWS Current Service</param>
    /// <param name="bodyText">Message Text</param>
    /// <param name="subject">Message Original Subject</param>
    public static void Reply(EmailMessage message, Int32 index, ExchangeService service, String bodyText, String subject)
    {
        var replyWorker = new BackgroundWorker();

        replyWorker.DoWork += (sender, args) =>
        {
            bool replyToAll = false;
            ResponseMessage responseMessage = message.CreateReply(replyToAll);
            responseMessage.BodyPrefix = bodyText;
            responseMessage.Subject = subject;
            responseMessage.SendAndSaveCopy();
        };

        replyWorker.RunWorkerCompleted += (sender, args) =>
        {
            if (args.Error != null)
                MessageBox.Show(args.Error.ToString());

            ReplyMail.GlobalAccess.Invoke(new Action(() =>
            {
                ReplyMail.GlobalAccess.mailSentPic.Visible = true;
                ReplyMail.GlobalAccess.MailSentTxt.Visible = true;
                ReplyMail.GlobalAccess.button2.Visible = true;
            }));
        };
        replyWorker.RunWorkerAsync();

    }

    /// <summary>
    /// Forward an E-mail, lets you introduce recipients.
    /// </summary>
    /// <param name="message">EMAILMESSAGE</param>
    /// <param name="index">Mail position on the treeview</param>
    /// <param name="service">EWS Service</param>
    /// <param name="addresses">List with the mail adresses that the user is forwarding to</param>
    public static void Forward(EmailMessage message, Int32 index, ExchangeService service, List<EmailAddress> addresses)
    {
        var forwardWorker = new BackgroundWorker();

        forwardWorker.DoWork += (sender, args) =>
        {
            message.Forward(message.Body.Text, addresses);
        };

        forwardWorker.RunWorkerCompleted += (sender, args) =>
        {
            if (args.Error != null)
                MessageBox.Show(args.Error.ToString());

            ReplyMail.GlobalAccess.Invoke(new Action(() =>
            {
                ReplyMail.GlobalAccess.mailSentPic.Visible = true;
                ReplyMail.GlobalAccess.MailSentTxt.Visible = true;
                ReplyMail.GlobalAccess.button2.Visible = true;
            }));
        };
        forwardWorker.RunWorkerAsync();            
    }

    /// <summary>
    /// Send a single E-Mail
    /// </summary>
    /// <param name="service">EWS Service</param>
    /// <param name="subject">EMAILMESSAGE subject</param>
    /// <param name="bodyText">EMAILMESSAGE body.text</param>
    /// <param name="destination">EMAILADDRESS from receiver</param>
    public static void Send(ExchangeService service, String subject, String bodyText, String destination)
    {
        var sendWorker = new BackgroundWorker();

        sendWorker.DoWork += (sender, args) =>
        {
            EmailMessage message = new EmailMessage(service);
            message.Subject = subject;
            message.Body = bodyText;
            message.ToRecipients.Add(destination);
            message.SendAndSaveCopy();
        };

        sendWorker.RunWorkerCompleted += (sender, args) =>
        {
            if (args.Error != null)
                MessageBox.Show(args.Error.ToString());

            ReplyMail.GlobalAccess.Invoke(new Action(() =>
            {
                ReplyMail.GlobalAccess.mailSentPic.Visible = true;
                ReplyMail.GlobalAccess.MailSentTxt.Visible = true;
                ReplyMail.GlobalAccess.button2.Visible = true;
            }));
        };
        sendWorker.RunWorkerAsync();           
    }
}

}

  • Remove From My Forums
  • Question

  • User1760698851 posted

    I have WEB API & Web application both running on same server. I have enabled both for windows authentication. Web Application is consuming WEB API

    code :

    public static List<Course> GetCourses()
    
    {
    
        List<Course> courseList = new List<Course>();
        webClient.Credentials = new NetworkCredential("xxx", "yyy","UAT");
        string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");
    
        dynamic dynObj = JsonConvert.DeserializeObject(courses);
            foreach (var data in dynObj)
               {
                   Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
                   courseList.Add(course);
               }
         return Course.SortCoursesAlpha(courseList);
    
    }

    This works  locally when I tried to debug from my local machine where it works without popping username & password

    . But after publishing to a server and when I tried to see if it works . It pops up the username & password and gives me :

    Server Error in ‘/’ Application.


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

    Description: An
    unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

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

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


    Stack Trace: 

    [WebException: The remote server returned an error: (401) Unauthorized.]
       System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +283
       System.Net.WebClient.DownloadString(Uri address) +100
       System.Net.WebClient.DownloadString(String address) +29
       StudentMailer.Mailer.ApiHandler.GetCourses() in c:StudentMailertrunkStudentMailerStudentMailerMailerApiHandler.cs:42
       StudentMailer._Default.Page_Load(Object sender, EventArgs e) in c:StudentMailertrunkStudentMailerStudentMailerDefault.aspx.cs:30
       System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
       System.Web.UI.Control.OnLoad(EventArgs e) +92
       System.Web.UI.Control.LoadRecursive() +54
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
    

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

    web application application pool details :

    application pool : v4.0  Integrated LocalSystem  

Answers

  • User-2057865890 posted

    Hi Jim,

    You could create a registry key on the machine that is trying to access the server, and white list the domain you are trying to hit.

    • Click Start, click Run, type regedit, and then click OK.
    • In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
    • Right-click MSV1_0, point to New, and then click Multi-String Value.
    • Type BackConnectionHostNames, and then press ENTER.
    • Right-click BackConnectionHostNames, and then click Modify.
    • In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
    • Quit Registry Editor, and then restart the IISAdmin service.

    reference: https://support.microsoft.com/en-us/kb/896861 

    Best Regards,

    Chris

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1760698851 posted

    Hi Chris,

    Thanks for all your effort  you made . Finally, it is working :

    It was not straight forward :

    On  the Server , I wasn’t able to access the WEB API & ASP.NET WEB application which was using WEB API to populate the data locally . ( Was helpfull to test locally on server)

    step 1 :

    You could create a registry key on the machine that is trying to access the server, and white list the domain you are trying to hit.

    • Click Start, click Run, type regedit, and then click OK.
    • In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
    • Right-click MSV1_0, point to New, and then click Multi-String Value.
    • Type BackConnectionHostNames, and then press ENTER.
    • Right-click BackConnectionHostNames, and then click Modify.
    • In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
    • Quit Registry Editor, and then restart the IISAdmin service.

    reference: https://support.microsoft.com/en-us/kb/896861 

    Step 2: Install windows Authentication on IIS  &  Windows Authentication ( under IIS -> Authentication )  on both WEB API & ASP.NET web application

    Step 3: 

    My final code was ( if you are accessing WEB API & web application from same machine using windows authentication ) from a web application .

    private static  WebClient wc = new WebClient();
    
    
    public static List<Course> GetCourses()
    
    {
    
        List<Course> courseList = new List<Course>();
         wc.UseDefaultCredentials = true;
        string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");
        dynamic dynObj = JsonConvert.DeserializeObject(courses);
            foreach (var data in dynObj)
               {
                   Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
                   courseList.Add(course);
               }
         return Course.SortCoursesAlpha(courseList);
    
    }
    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

SharePoint Online training courses

In this SharePoint tutorial, we will discuss how to resolve The remote server returned an error (401) Unauthorized error in SharePoint Online/2016/2013 with CSOM or PowerShell. The remote server returned an error (401) Unauthorized error can come in SharePoint Online as well as SharePoint 2016/2013.

I have faced the (401) Unauthorized error while working with csom in both SharePoint Online and SharePoint 2016 and with PowerShell.

First, we will discuss how to resolve the issue which comes while working with SharePoint 2016/2013 client object model (csom/c#). The error comes are An unhandled exception of type ‘System.Net.WebException’ occurred in Microsoft.SharePoint.Client.dll. Additional information: The remote server returned an error: (401) Unauthorized.

We were using SharePoint 2016/2013 .Net client object model to retrieve site information using visual studio 2015/2017.

We were using Microsoft.SharePoint.Client.dll & Microsoft.SharePoint.Client.Runtime.dll. We were writing the below code inside a console application for SharePoint.

This is a simple code we were writing to retrieve web title from the SharePoint 2016 site collection.

private void GetSiteDetails()
{
using (ClientContext context = new ClientContext("http://mypc/sites/MySP2016SiteCollection/"))
{
context.Credentials = new NetworkCredential(@"SP2016Bijay", "mypassword");
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
lblResult.Text = web.Title;
}
}

But in the ExecuteQuery() method it gave the error like below:

An unhandled exception of type ‘System.Net.WebException’ occurred in Microsoft.SharePoint.Client.dll

Additional information: The remote server returned an error: (401) Unauthorized.

at System.Net.HttpWebRequest.GetResponse()
at Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()
at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()
at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at ClientObjectModelDemo17March.Form1.GetSiteDetails() in E:UsersAdministratordocumentsvisual studio 2015ProjectsClientObjectModelDemo17MarchClientObjectModelDemo17MarchForm1.cs:line 99
at ClientObjectModelDemo17March.Form1.button2_Click(Object sender, EventArgs e) in E:UsersAdministratordocumentsvisual studio 2015ProjectsClientObjectModelDemo17MarchClientObjectModelDemo17MarchForm1.cs:line

the remote server returned an error (401) unauthorized sharepoint csom

the remote server returned an error (401) unauthorized sharepoint csom

The remote server returned an error: (401) Unauthorized SharePoint CSOM

We need to provide credentials when we are trying to connect to SharePoint on-premise or SharePoint online site. In my case I was not providing the credentials correctly. So the above error was coming.

The issue was in the below line:

context.Credentials = new NetworkCredential(@"SP2016Bijay", "mypassword");

When I change the credentials the issue did not came.

context.Credentials = new NetworkCredential(@"MySPAdministrator", "Qwe@12345");

Here basically we need to check the credentials are correct or not. If you provide the correct credentials then it will work fine.

the remote server returned an error 401 unauthorized SharePoint provider hosted app

The same the remote server returned an error 401 unauthorized can appear also in SharePoint Provider-hosted app or add-ins.

If after giving correct credentials, still, the error exists, then you can try to set AuthenticationMode to Default like below:

using (ClientContext context = new ClientContext("http://tsinfotech/sites/TSINFOTECH/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new NetworkCredential(@"TSInfoAdministrator", "Welcome@123");

//Rest of your code

}

If you are facing the same issue in Provider hosted apps, then you can try the below solution also.

Open web.config file of asp.net web form application and write the below code.

<appSettings>
   <add key="aspnet:AllowAnonymousImpersonation" value="false" />
</appSettings>

The remote server returned an error (401) Unauthorized SharePoint PowerShell

Recently while working with PowerShell SharePoint using SharePoint online management shell we got the below error which says:

Connect-SPOService : The remote server returned an error: (401) Unauthorized.
At line:2 char:1
Connect-SPOService -Url http://onlysharepoint2013-admin.sharepoint.com/ -credent …
CategoryInfo : NotSpecified: (:) [Connect-SPOService], WebException
FullyQualifiedErrorId : System.Net.WebException,Microsoft.Online.SharePoint.PowerShell.ConnectSPOService

Get-SPOSite : No connection available. Use Connect-SPOService before running this CmdLet.
At line:3 char:1
Get-SPOSite
CategoryInfo : NotSpecified: (:) [Get-SPOSite], InvalidOperationException
FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Online.SharePoint.PowerShell.GetSite

We were connecting to SharePoint online site using SharePoint online management shell.

Below was the command we were trying.

Import-Module Microsoft.Online.SharePoint.Powershell -Verbose
Connect-SPOService -Url http://onlysharepoint2013-admin.sharepoint.com/ -credential Bhawana@OnlySharePoint2013.onmicrosoft.com
Get-SPOSite

the remote server returned an error (401) unauthorized sharepoint powershell

the remote server returned an error (401) unauthorized sharepoint powershell

We were giving the -admin site also in the Url parameter, but still, the issue was coming.

the remote server returned an error (401) unauthorized SharePoint PowerShell

We found out that the URL was creating the issue. we were providing http://onlysharepoint2013-admin.sharepoint.com/ (with http not with https)

We need to provide the URL as https URL. Office 365 urls are always https.

So we replace the URL like https://onlysharepoint2013-admin.sharepoint.com/

This resolved the issue. We did not receive any The remote server returned an error: (401) Unauthorized error.

You may like following SharePoint csom tutorials:

  • Create subsite in SharePoint 2016 programmatically using csom visual studio 2017
  • the remote server returned an error 500 internal server error. the sharepoint client object model
  • the remote server returned an error (403) forbidden SharePoint client object model
  • Get list item by id using jsom (JavaScript object model) in SharePoint Online/2016/2013
  • Get all SharePoint subsites programmatically using PnP CSOM
  • Exception calling ExecuteQuery with 0 argument(s): Unable to connect to the remote server error in PowerShell SharePoint Online

The same solution applies to the below error messages which are related:
the remote server returned an error (401) unauthorized. SharePoint online,
connect-pnponline : the remote server returned an error: (401) unauthorized., the remote server returned an error (401) unauthorized SharePoint PowerShell, the remote server returned an error 401 unauthorized, the remote server returned an error 401 unauthorized SharePoint, the remote server returned an error 401 unauthorized SharePoint csom, the remote server returned an error 401 unauthorized SharePoint provider hosted app, the remote server returned an error (401) unauthorized office 365, the remote server returned an error (401) unauthorized SharePoint 2013/2016.

Bhawana Rathore

Hello Everyone!! I am Bhawana a SharePoint MVP and having about 10+ years of SharePoint experience as well as in .Net technologies. I have worked in all the versions of SharePoint from wss to Office 365. I have good exposure in Customization and Migration using Nintex, Metalogix tools. Now exploring more in SharePoint 2016 🙂 Hope here I can contribute and share my knowledge to the fullest. As I believe “There is no wealth like knowledge and no poverty like ignorance”

The 401 Unauthorized Error is an HTTP response status code indicating that the client could not authenticate a request. 

In this article, we’ll examine the 401 Error in more detail. We’ll show you how to diagnose and debug this error within your own application.

Server- or Client-Side?

All HTTP response status codes in the 4xx category are client error responses. These messages contrast with server error responses in the 5xx category, such as the 503 Service Unavailable Error.

However, the appearance of a 401 error code or any 4xx error doesn’t necessarily mean the client is the issue, where the client is the web browser or device used to access the application. 

For example, if you’re trying to diagnose an issue with your application, you can ignore most client-side code. This includes HTML, cascading style sheets (CSS), client-side JavaScript, etc.

On the other hand, this doesn’t rule out the client as the actual cause of a 401 Unauthorized Error. While it’s probably not the HTML or CSS, it could be that the client may be sending a request that doesn’t contain any authentication information. 

Even though the 401 Unauthorized Error is a client error response, it doesn’t mean we can rule out the server as the culprit. The server is still the network object producing the 401 Unauthorized Error and returning it as the HTTP response code to the client.

We’ll go over all this in detail in the following sections.

Start With a Thorough Application Backup

Before attempting any changes to the system, make sure to perform a full backup of your application, database, etc. If you can, create a complete copy of the application onto a secondary staging server. This will give you a clean testing ground to test all potential fixes without threatening the sanctity of your live application.

As discussed in the introduction, a 401 Unauthorized Error indicates that the client (the web browser, in most cases) has requested a restricted resource (such as a web page) from the server. Still, the client has failed to provide valid authentication credentials. 

A 401 Error might occur in one of a handful of possible scenarios:

  • The client sent its authentication credentials to the server, but the server rejected the credentials.
  • The client failed to provide any authentication credentials within the request.
  • The client is banned. Some applications use 401 Unauthorized Errors to restrict access requests from specific IP addresses.

Troubleshooting on the Client-Side

Since the 401 Unauthorized Error is a client error response code, it’s best to start by troubleshooting potential client-side issues. 

Here are a handful of tips to try on the browser or device giving you problems.

Check the Requested URL

The most common cause of a 401 Unauthorized Error is an incorrect URL. As discussed before, web servers will disallow access to improper URLs. This could be anything from trying to access a file directory via a URL to gaining access to a private page meant for other users. 

Double-check the exact URL returning the 401 error to ensure that it is the actual resource you intend to request.

Clear Relevant Cookies

HTTP cookies are tiny pieces of data stored on your local device. Websites and applications then use cookies to «remember» information about this particular browser and/or device. 

Most modern web apps use cookies to store user authentication status. These cookies inform the web application which user is currently active and what kind of authorization to give the current client (browser). When a 401 Unauthorized Error occurs, the problem could be invalid or corrupted cookies, causing improper authentication for the server. 

You only need to worry about cookies relevant to the website or application causing the problem in most cases. Cookies are stored based on the location of the domain, meaning you can remove only cookies that match the website domain (e.g., airbrake.io).

However, if you’re not experienced with manually removing certain cookies, it’s easier to clear all cookies at once.

Here are a few how-to articles to clear cookies depending on your browser:

  • Google Chrome
  • Internet Explorer
  • Microsoft Edge
  • Mozilla Firefox
  • Safari

Clear the Cache

Like cookies, local browser caches can cause 401  Unauthorized Error to appear. A cache is a collection of storage that retains local copies of web content on your device for later use. A browser’s cache typically stores compressed snapshots of webpages you frequently visit, including images and other binary data your browser often accesses.

With a local copy of these resources on your device, your browser doesn’t need to spend the time or bandwidth to download identical data every time you return to the same page. 

For example, every time you open up Facebook, your page downloads content from the cache on your local device.

Since your browser’s cache stores local copies of web content and resources, it’s possible that a change to the live version of your application is conflicting with the cached version already on your device, causing a 401 Unauthorized Error. 

Try clearing your browser’s cache to see if that fixes the issue. As with cookies, clearing the cache is browser-dependent. Here are a few links to that relevant documentation for the most popular browsers:

  • Google Chrome
  • Internet Explorer
  • Microsoft Edge
  • Mozilla Firefox
  • Safari

Log Out and Log In

Since the application in question likely contains some form of authentication, the last client-side step to try is to log out and then log back in. 

Clearing browser cookies will usually log you out automatically the next time you load the page. So, all you need to do is log back in. 

In some situations, the application may be running into a problem with your previous session, which is a string that the server sends to the client to identify that client during future requests.

Your device stores session tokens (session strings) via cookies. The client then transfers these tokens to the server during a request. The problem is if the server doesn’t recognize the session token sent by the client or the token is invalid. This will result in a 401 error.

For most web applications, logging out and logging back in will force the local session token to be recreated.

Debugging Common Platforms

Common software packages and content management systems (CMS) can also be responsible for the 401 Unauthorized Error. If you’re seeing this error, take a look at the stability and functionality of these platforms. 

The most common content management systems — like WordPress, Joomla!, and Drupal — are all typically well-tested. Still, once you start making modifications to the underlying extensions or PHP code (the language in which nearly all modern content management systems are written), it’s too easy to cause an unforeseen issue resulting in a 401 error.

Here are a few tips to help you troubleshoot some of these popular software platforms. 

Rollback Recent Upgrades

If you recently updated your CMS and now you’re seeing a 401 error, consider rolling back to the previous version on your CMS. 

Similarly, any extensions or modules you may have recently upgraded can also cause server-side issues. If you believe this is why you’re seeing an error, revert to your previous CRM version. 

However, certain CMSs don’t provide a version downgrade capability in some cases. This indicates that the base application, along with each new version released, is stable and bug-free. You’ll typically see this with more popular platforms.

Uninstall New Extensions, Modules, or Plugins

Extensions, modules, or plugins serve the same purpose across every system. They improve the capabilities and features of your CMS. 

But you should be cautious with extensions because they can take full control of the system and make virtually any changes to the PHP code, HTML, CSS, JavaScript, or database. As such, uninstall any new extensions that you added before the 401 error.

Check for Unexpected Database Changes

It’s worth noting that if you uninstall an extension through the CMS dashboard, this doesn’t guarantee that changes made by the extension will fully revert. This is particularly true for WordPress extensions that have been given carte blanche within the application. This often includes full access rights to the database. 

There are scenarios where an extension may modify database records that don’t “belong” to the extension itself. The extension may not know how to revert alterations to database records in those scenarios, even if you uninstall it.

If you’re reasonably convinced an extension is a likely culprit for the status code 401 error, open the database and manually look through tables and records likely modified by the extension.

Troubleshooting on the Server-Side

If you aren’t running a CMS application or you’re confident the 401 Unauthorized Error isn’t related to your CSM — here are some additional tips to help you troubleshoot what might be causing the issue on the server-side.

RFC 7235 is the official standards document outlining how Hypertext Transfer Protocol (HTTP:/1.1): Authentication should be performed on the web. This is just one of the thousands of documents published by the Internet Engineering Task Force, an open community dedicated to creating open Internet standards. 

According to the RFC 7235, a 401 Unauthorized Error response code sent by a server must also include the WWW-Authenticate response header, which contains one or more challenges. Each challenge is a string indicating how proper authentication can be obtained to access the requested resource. 

The syntax of a WWW-Authenticate header is: WWW-Authenticate: <type> realm=<realm>. The <type> value can be one of several valid authentication schemes. <realm> describes the area or “realm” that can be accessed. 

For example, a WWW-Authenticateheader of WWW-Authenticate: Basic realm=»Access to the production server» indicates to the client that authentication requests should be Basic (an id and password credential combination). This will give access to the “production server.”

With this knowledge in hand, you can attempt to diagnose the 401 Unauthorized Error you’re seeing on your application by confirming that the application is sending a valid WWW-Authenticate response header. This header can give you extra information that may lead to a solution, such as showing which particular authentication schemes are expected by the server.

You can view HTTP headers either from the server or the client web browser. View headers in Google Chrome by pressing F12 to open the developer console, select the Network tab, then load or reload the specific page/resource showing the 401 Error. This will show the list of all resources involved in the transaction, including everything from the actual document to individual images. 

Sort the results by the Status by clicking the Status table header, then find the “401” status code. Select that entry in the list, and you should be able to view the Headers tab for that request. Look under Response Headers for the associated WWW-Authenticate header.

Check Your Web Server Configuration

Most modern web servers provide one or more configuration files that allow you to easily adjust the server behavior based on a wide range of circumstances. For example, the server may reject requests to certain directories or URLs, resulting in a 401 Unauthorized Error.

Configuration options for each type of web server can vary dramatically. Here’s a list of a few popular servers:

  • Apache
  • Nginx
  • IIS
  • Node.js
  • Apache Tomcat

Look Through the Logs

Nearly every web application will keep some form of server-side logs. Application logs are the history of what the application did. The log will show requested pages, connected servers, database results, etc. Server logs are related to the actual hardware running the application and will often provide details about the health and status of all connected services or even just the server itself. Google “logs [PLATFORM_NAME]” if you’re using a CMS, or “logs [PROGRAMMING_LANGUAGE]” and “logs [OPERATING_SYSTEM]” if you’re running a custom application, to get more information on finding the logs in question.

Debug Your Application Code or Scripts

Finally, if all else fails, it may be that a problem in some custom code within your application is causing the issue. Try to diagnose where the issue may be coming from by manually debugging your application and parsing through application and server logs. 

Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process, allowing you to recreate the exact scenario where the 401 Unauthorized Error occurred.

No matter the cause — and even if you managed to fix it this time — the appearance of an issue like the 401 Unauthorized Error within your own application is a good indication you may want to implement an error management tool. Error monitoring will help you automatically detect errors and report them to you when they occur. Here’s another blog you can read to learn more about error monitoring vs. logging.  

Airbrake’s error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state-of-the-art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. Plus, Airbrake makes it easy to customize exception parameters, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today and see why so many of the world’s best engineering teams use Airbrake!

Note: We published this post in November 2017 and recently updated it in May 2022.

Written By: Frances Banks

Понравилась статья? Поделить с друзьями:
  • The remote name could not be resolved ошибка
  • The realtek network controller was not found ошибка
  • The real author of limit adjuster is fastman92 ошибка
  • The pivot table field name is not valid ошибка
  • The phantom pain ошибка при запуске