System net webexception the remote server returned an error 401 unauthorized

User1760698851 posted
  • 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

title author description ms.date ms.assetid msc.legacyurl msc.type

Troubleshooting Common Problems with Web Deploy

ehamai

This walkthrough shows how to diagnose and fix common problems with Web Deploy, including common errors seen while publishing from Visual Studio 2010. Loggin…

04/20/2012

582eff55-c99e-4eeb-8642-d8334a94c3c2

/learn/publish/troubleshooting-web-deploy/troubleshooting-common-problems-with-web-deploy

authoredcontent

Troubleshooting Common Problems with Web Deploy

by Elliott Hamai

This walkthrough shows how to diagnose and fix common problems with Web Deploy, including common errors seen while publishing from Visual Studio 2010.

Logging

When you run into issues with Web Deploy, there are several logging options depending on where the problem occurred. By default, Web Deploy logs to the Event Log under Applications > Microsoft Web Deploy. This is great place to start looking for errors on the destination server.

In the unlikely case that you cannot diagnose the problem using the Event Log, here are some other options:

  1. To diagnose installation problems, Web Deploy MSI logs are placed under %programfiles%IISMicrosoft Web Deploy v3.
  2. If Web Management Service or Remote Agent Service fail to start at all, look at the event Event Log > System for Service Control Manager errors.
  3. You can further configure tracing for Web Management Service

Error Codes

For certain common error cases, Web Deploy will show a message and an error code which may be useful in getting more information to troubleshoot an issue. For a full list of error codes, see https://go.microsoft.com/fwlink/?LinkId=221672 .

Note that the error message may be different depending on how Web Deploy is invoked. For example, Microsoft WebMatrix chooses to show custom error messages instead of error codes whereas the command line will always show error codes if they are logged.

Installation

1. Could not install Web Deploy on a valid OS

Symptoms The OS is correct, the version and bitness of Web Deploy are correct, but the installation does not succeed.
Root Cause Unknown
Fix/Workaround Look in the install log, located in %programfiles%IISMicrosoft Web Deploy V2.

2. Web Deploy does not function after upgrade

Symptoms Web Deploy does not work after a version upgrade.
Root Cause Web Deploy does not restart services after an upgrade.
Fix/Workaround If you are upgrading an existing installation of Web Deploy, make sure to restart the handler and agent services by running the following commands at an administrative command prompt: · net stop msdepsvc & net start msdepsvc · net stop wmsvc & net start wmsvc

3. Could not install Web Deploy 32-bit version on 64-bit hardware

Symptoms Screenshot of the Microsoft Web Deployment Tool Setup dialog box. The text says that the thirty two bit version of Microsoft Web Deployment Tool cannot be installed on a sixty four bit edition of Microsoft Windows.
Root Cause Trying to install 32-bit on 64-bit OS is a check inside the Web Deploy MSI that will fail because it doesn’t support WoW64 mode.
Fix/Workaround Install the same version that matches the architecture of your OS.

4. Could not install Web Deploy 64-bit version on 32-bit hardware

Symptoms Screenshot of the Windows Installer dialog box. The text says that This installation package is not supported by this processor type. Contact your product vendor.
Root Cause Trying to install 64-bit on 32-bit OS is a check inside Web Deploy’s MSI that will fail.
Fix/Workaround Install the same version that matches the architecture of your OS.

5. Could not register the URL namespace due to pre-existing namespace

Symptoms Unable to install Web Deploy
Root Cause The URL namespace that Web Deploy tries to create during installation is already registered
Fix/Workaround · Remove the conflicting registration · Change Web Deploy URL during installation msiexec /i wdeploy.msi /passive ADDLOCAL=ALL LISTENURL=http://+:8080/MSDEPLOY2/. For more information about URL customization, see Customizing and Securing the Remote Service.

Remote Agent Service

1. Could not initialize Microsoft.Web.Deployment.Dll during start-up

Symptoms Remote Agent Service fails to start
Root Cause msdepsvc.exe or other files are missing from %programfiles%IISMicrosoft Web Deploy v2.
Fix/Workaround Re-install the product

2. Remote Agent Service is not started

Symptoms Microsoft.Web.Deployment.DeploymentAgentUnavailableException: Remote agent (URL http://DestinationServer /msdeployagentservice) could not be contacted. Make sure the remote agent service is installed and started on the target computer. —> System.Net.WebException: The remote server returned an error: (404) Not Found.
Root Cause Remote Agent Service is not started
Fix/Workaround Start the service — ex: net start msdepsvc

3. Trying to connect to server where HTTP is not listening or allowed

Symptoms Microsoft.Web.Deployment.DeploymentAgentUnavailableException: Remote agent (URL http://DestinationServer/msdeployagentservice) could not be contacted. Make sure the remote agent service is installed and started on the target computer. —> System.Net.WebException: Unable to connect to the remote server —> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it DestinationServer:80
Root Cause HTTP not listening
Fix/Workaround Make sure HTTP traffic is allowed to the Remote Agent Service

4. Trying to connect to server with Method Not Allowed error

Symptoms Microsoft.Web.Deployment.DeploymentException: Could not complete the request to remote agent URL ‘http://DestinationServer/‘. —> System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
Root Cause Request was picked up by IIS itself instead of MS Deploy, because the path to msdepsvc.exe is missing.
Fix/Workaround Change the URL to include to /MSDeployAgentService

5. Trying to access Remote Agent Service as a non-administrator

Symptoms Microsoft.Web.Deployment.DeploymentException: Could not complete the request to remote agent URL ‘http://DestinationServer/msdeployAgentService‘. —> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
Root Cause Remote Agent Service requires that the caller is a member of the Administrators group or from a domain account that has been added to the Administrators group. A local administrator which is not the built-in account will not work with the Remote Agent Service because of a bug in Web Deploy 2.0.
Fix/Workaround Provide administrative credentials

6. Remote Agent Service hangs during operation

Symptoms Service may stop responding for a long time, up to several hours
Root Cause Unknown
Fix/Workaround Stop the operation and attempt to repeat it

7. Client and server are not compatible (version mismatch)

Symptoms Timestamp=24638007621418 MsDepSvc.exe Error: 0 : An error occurred. The exception details are as follows: Microsoft.Web.Deployment.DeploymentClientServerException: The client and server are not compatible. The lowest version supported by the client is ‘7.1.538.0’. The highest version supported by the server is ‘7.1.537.0’.
Root Cause Some versions do not work together, so Web Deploy blocks them from working together. This is typically done to block pre-release versions from operating with released versions.
Fix/Workaround Match the versions

8. Remote Agent Service could not start listening on URL

Symptoms The Remote Agent Service could not start listening on the URL ‘{0}’. Make sure that the URL is not in use.
Root Cause Usually indicates a URL conflict.
Fix/Workaround Try reinstalling if you want the default URL or setting a custom URL as specified in the documentation. For more information about URL customization, see Customizing and Securing the Remote Service

Web Management Service

1. Web Management Service not started

Symptoms Web Management Service is not started.
Root Cause Unknown. The service should be started by default.
Fix/Workaround Start the Web Management Service service: Net Start WMSVC

2. Not Authorized: User not authorized by deployment handler rules

Symptoms Could not complete an operation with the specified provider <provider name> when connecting using the Web Management Service. This can occur if the server administrator has not authorized the user for this operation.
Root Cause A non-administrator user tried to perform a restricted action with a provider. This usually indicates that a matching delegation rule was not found. Either the username, provider, operation or provider path is wrong.
Fix/Workaround The workaround is to fix the delegation rule or create one. For more information about delegation rules, see Configure the Web Deployment Handler.

Case Study: Diagnosing Publishing Errors in Visual Studio 2010

This case study shows how to diagnose common errors encountered in Visual Studio 2010. The steps below walk through the series of errors you are likely to encounter when trying to publish from Visual Studio to a server that has not been correctly configured.

To collect the screenshots and errors below, we used a new ASP.NET MVC3 project. The destination server was a clean install of Windows Server 2008 R2 SP1 with IIS. No additional configuration was done.

The first error you are likely to encounter will look something like this in Visual Studio’s output window. To make it easier to read, the full text of the message is reproduced below the screenshot.

Screenshot of the Error List page. An error description is shown.

Web deployment task failed.(Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.)

This error indicates that you cannot connect to the server. Make sure the service URL is correct, firewall and network settings on this computer and on the server computer are configured properly, and the appropriate services have been started on the server.

Error details:

Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.

Unable to connect to the remote server

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.211:8172

Is the web management service installed? On the destination server, open IIS Manager and select the machine name node. In the Features view, scroll down to the Management section and look for these Icons:

Screenshot of the I I S Manager Permissions icon, the I I S Manager Users icon, and the Management Service icon.

If they are not there, you need to install the Web Management Service.

· Through the «Add Role Services» dialog in Server Manager.

· Through the Web Platform Installer from the Products tab. Select «Server» in the left column and choose «IIS: Management Service».

Note that after you install the Management Service, you will need to start it, as it is not started automatically.

Once the Web Management Service is installed, Visual studio may show this error:

Screenshot of an error page in Visual Studio. An error description is shown.

Web deployment task failed.(Could not connect to the destination computer («deployserver») using the specified process («The Web Management Service») because the server did not respond. Make sure that the process («The Web Management Service») is started on the destination computer.)

Could not connect to the destination computer («deployserver») using the specified process («The Web Management Service») because the server did not respond. Make sure that the process («The Web Management Service») is started on the destination computer.

The remote server returned an error: (403) Forbidden.

Is the Web Management Service configured to allow remote connections? Start IIS Manager and double-click the Management Service icon, and verify that «Enable Remote Connections» is checked. You must stop the service to make changes, so be sure to restart it.

Screenshot of the Management Service page. The Enable remote connections checkbox is checked.

Is Windows Firewall blocking the request? The Web Management Service creates an Inbound rule named «Web Management Service (HTTP Traffic-In)», and enables it. Verify this rule is enabled by going to Start->Administrative tools-> «Windows Firewall with Advanced Security». Click «Inbound Rules» and find the Web Management rule in the list. It should be enabled for all profiles.

If you are using a 3rd party firewall, make sure inbound TCP connections on port 8172 are allowed.

If Visual Studio is able to contact the Management Service, the error message changes:

Screenshot of the Visual Studio Error List page. A description of an error is shown.

Web deployment task failed.(Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.)

The requested resource does not exist, or the requested URL is incorrect.

Error details:

Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.

The remote server returned an error: (404) Not Found.

If you look in the Web Management Service log under %SystemDrive%InetpublogsWMSvc on the destination server, you will see an entry that looks like

[!code-consoleMain]

Is Web Deploy installed? You can verify web deploy is installed by going to the «Programs and Features» control panel and looking for «Microsoft Web Deploy 2.0» in the list of installed programs. If it is not there, you can install it via the Web Platform Installer by going to the «Products» tab. It is listed as «Web Deployment Tool 2.1».

Is the Web Deployment IIS7 Deployment Handler installed? If Web Deploy is installed and you still get this error, make sure the «IIS 7 Deployment Handler» feature in Web Deploy is installed. In «Add Remove Programs», find «Microsoft Web Deploy 2.0», right click and choose «Change». In the Wizard that comes up, click next on the first page, and then choose «Change» on the second page. Add «IIS 7 Deployment Handler» and everything under it.

SCreenshot of the Microsoft Web Deploy two dot zero Setup wizard. The Web Development Framework option is selected.

Click Next to complete the Wizard.

Once Web Deploy and the Web Management Service are correctly configured, you will need to set up Web Management Service delegation rules to allow users to update content. For permissions issues, there are several different errors you may see in Visual Studio. For example:

Screenshot of the Visual Studio Error List page. An error appears along with a description of the error.

Web deployment task failed.(Connected to the destination computer («deployserver») using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site.)

Make sure the site name, user name, and password are correct. If the issue is not resolved, please contact your local or server administrator.

Error details:

Connected to the destination computer («deployserver») using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site.

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

In the Web Management Service log, you will see:

[!code-consoleMain]

[!code-consoleMain]

The highlighted HTTP status in the Visual Studio output is an Access Denied error. The highlighted Win32 status in the error log maps to «Logon failure: unknown user name or bad password». This is a simple logon failure. If the user is authenticated, but does not have the rights needed to publish, the log entry will look like

[!code-consoleMain]

You will need to setup delegation for this user per the instructions at https://www.iis.net/learn/publish/using-web-deploy/configure-the-web-deployment-handler

If the account is able to log in, but has not been granted the rights needed to publish the content, you will see

Screenshot of the Visual Studio Error List page with an error description. The web deployment task has failed.

Web deployment task failed. (Unable to perform the operation («Create Directory») for the specified directory («bin»). This can occur if the server administrator has not authorized this operation for the user credentials you are using.

The WMSvc log will show HTTP 200 responses for these requests. The most likely cause is file system permissions. Web Deploy will also write events to the «Microsoft Web Deploy» service log. To view it, open the event viewer and go to «Applications and Services Logs» ->»Microsoft Web Deploy».

Screenshot of the Visual Studio Error List page. A description of an error says that the Web deployment task failed.

For this particular error, the event log contains extra detail (truncated for brevity):

[!code-consoleMain]

This message tells you where permissions need to be granted for this particular error. Another permissions error you may see in Visual Studio is

Screenshot of the Event Viewer navigation tree. The Microsoft Web Deploy option is selected.

Web deployment task failed.((5/12/2011 11:31:41 AM) An error occurred when the request was processed on the remote computer.)

(5/12/2011 11:31:41 AM) An error occurred when the request was processed on the remote computer.
The server experienced an issue processing the request. Contact the server administrator for more information.

This particular error does not give you much to go on, but the picture becomes much clearer if you look at the Web Deploy error log in Event Viewer.

[!code-consoleMain]

From this, we can see that User1 does not have rights to set security information. In this case, the user does not have Modify permissions on the content. Granting «Change Permissions» to the content resolves the problem.

If you cannot browse a .NET 4.0 application after it has been successfully published, it could be that .NET 4.0 has not been registered correctly with IIS. Other symptoms are that .NET 4.0 is installed, but there are no .NET 4.0 application pools or handler mappings in IIS. This happens when .NET 4.0 is installed before IIS was installed. To fix this problem, start an elevated command prompt and run this command:

[!code-consoleMain]

Содержание

  1. Что делать с ошибкой 401 Unauthorized Error – методы исправления
  2. Как исправить ошибку 401
  3. Другие варианты ошибки 401
  4. Ошибки подобные 401
  5. Server Error in ‘/’ Application.
  6. The remote server returned an error: (401) Unauthorized.
  7. Answers
  8. Ошибка 401 Unauthorized: что означает и как исправить?
  9. Что значит ошибка 401 Unauthorized?
  10. Что делать при ошибке 401 Unauthorized, если вы обычный посетитель сайта?
  11. Как исправить ошибку 401 Unauthorized, если вы владелец сайта?
  12. Ошибка сервера 401: что это за ошибка и как ее исправить
  13. Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя
  14. Устранение ошибки 401 администратором веб-ресурса
  15. Дополнительная информация об ошибке с кодом 401

Ошибка 401 Unauthorized Error – это код состояния HTTP, который означает, что страница, к которой вы пытались получить доступ, не может быть загружена, пока вы не войдете в систему с действительным идентификатором пользователя и паролем.

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

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

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

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

Как исправить ошибку 401

Проверьте на наличие ошибок в URL. Возможно, ошибка 401 Unauthorized возникла, потому что URL-адрес был введен неправильно, или выбранная ссылка указывает на неправильный URL-адрес, предназначенный только для авторизованных пользователей.

Если вы уверены, что URL-адрес действителен, посетите главную страницу веб-сайта и найдите ссылку с надписью «Логин» или «Безопасный доступ». Введите здесь свои учетные данные, а затем повторите попытку.

Если у вас нет учетных данных или вы забыли свои, следуйте инструкциям на веб-сайте для настройки учетной записи или изменения пароля.

Если вам трудно вспоминать свои, храните их в диспетчере паролей, чтобы приходилось помнить только один пароль.

Перезагрузите страницу. Как бы просто это не показалось, закрытия страницы и её повторное открытие может помочь исправить ошибку 401, но только если она вызвана ошибочно загруженной страницей.

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

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

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

    Коды ошибок Microsoft IIS 401
    Ошибка Объяснение
    401,1 Войти не удалось.
    401,2 Ошибка входа в систему из-за конфигурации сервера.
    401,3 Несанкционированный доступ из-за ACL на ресурс.
    401,4 Авторизация не пройдена фильтром.
    401,5 Авторизация блокирована приложением ISAPI/CGI.
    401,501 Доступ запрещен: слишком много запросов с одного и того же клиентского IP; Ограничение динамического IP-адреса – достигнут предел одновременных запросов.
    401,502 Запрещено: слишком много запросов с одного IP-адреса клиента; Ограничение динамического IP-адреса – достигнут максимальный предел скорости запросов.
    401,503 Отказ в доступе: IP-адрес включен в список запрещенных IP
    401,504 Отказ в доступе: имя хоста включено в список запрещенных

    Ошибки подобные 401

    Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке: 400 Bad Request, 403 Forbidden, 404 Not Found и 408 Request Timeout.

    Также существует ряд кодов состояния HTTP на стороне сервера, например, часто встречающийся 500 Internal Server Error.

    Источник

    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.

    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.

    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

    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.

    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)

    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.

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

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

    Источник

    Ошибка 401 Unauthorized: что означает и как исправить?

    Сегодня рассмотрим такую специфическую ошибку как 401 Unauthorized Error. Почему специфическую? Потому что обычные пользователи интернета практически никогда не встречаются с данной ошибкой. Но обо всем по порядку.

    Что значит ошибка 401 Unauthorized?

    Ошибка 401 Unauthorized («Отказ в доступе») — эта ошибка означает, что при попытке открыть веб-страницу сайта пользователем возникли проблемы с его авторизацией или аутентификацией.

    Основная суть. Пользователь пытается открыть страницу. Сайт возвращает страницу с HTTP заголовком WWW-Authenticate (кстати, страница также с кодом 401 Unauthorized), в котором перечислены параметры системы аутентификации. Браузер запрашивает логин и пароль у пользователя, которые передаются в заголовке Authorization обратно к сайту (в соответствии с ранее полученными настройками системы безопасности). Если проверка прошла, то пользователю предоставляется дальше доступ к странице. В противном случае появляется ошибка 401 Unauthorized.

    Кстати, стоит понимать, что данная ошибка отличается от 403 Forbidden, хотя и также связана с настройками безопасности.

    Возможные причины возникновения ошибки 401 Unauthorized:

    1. Некорректно введенные логин или пароль (или их отсутствие). Пользователь что-то некорректно ввел.

    2. Недостаточно прав для доступа. Например, в каждом сайте вполне нормальным явлением считается то, что у обычного пользователя нет доступа к административной части сайта.

    3. Ошибки в настройках или коде сайта. Такое тоже бывает.

    Варианты возможных текстовых уведомлений:

    1. HTTP Error 401 — Ошибка авторизации.

    2. Требуется авторизация.

    3. 401 Несанкционированный доступ.

    4. 401 Unauthorized.

    5. Authorization Required.

    Что делать при ошибке 401 Unauthorized, если вы обычный посетитель сайта?

    Рассмотрим что вы можете сделать, если вы обычный пользователь и столкнулись с ошибкой 401 Unauthorized:

    1. Введите корректные логин и пароль. Ошибка 401 означает ошибку в авторизации или аутентификации, поэтому стоит проверить правильность введенных вами логина и пароля.

    2. Проверьте корректность URL адреса страницы веб-сайта. Если вы не ожидали увидеть 401 Unauthorized (скажем, постоянно открывали сайт без проблем), то вполне нормальным действием будет проверить корректность адреса.

    3. Попробуйте открыть страницу через время или с другого браузера. Вполне может быть так, что автор сайта что-то делает с этим самым веб-сайтом. Поэтому стоит подождать какое-то время и попробовать еще раз открыть веб-страницу. Так же может быть так, что ошибка 401 возникает из-за браузера (мало ли чего), поэтому стоит попробовать открыть страницу другим браузером (или с другого компьютера).

    4. Напишите автору сайта. Как минимум узнаете причину или возможное время восстановления доступа.

    Как исправить ошибку 401 Unauthorized, если вы владелец сайта?

    Теперь рассмотрим как исправить ошибку 401 Unauthorized владельцу сайта:

    1. Проверьте URL и логин с паролем. Владелец сайта это тоже пользователь сайта, поэтому проверить адрес страницы и корректность ввода логина с паролем будет не лишним действием.

    2. Проверьте настройки и код сайта. Если же вам сайт делал кто-то иной, то попросите его проверить.

    3. Напишите хостеру. Если вы все проверили и проблем не обнаружили, то нужно писать хостеру.

    Понравилась заметка? Тогда время подписываться в социальных сетях и делать репосты!

    Источник

    Ошибка сервера 401: что это за ошибка и как ее исправить

    Появление сообщения об ошибке 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, приложить скриншот.
    • При отсутствии проблем на стороне хостинг-провайдера можно внести следующие изменения в настройки сайта с помощью строки Disallow:/адрес проблемной страницы. Запретить индексацию страницам с ошибкой в «rоbоts.txt», после чего добавить в файл «.htассеss» строку такого типа:

    Где в поле /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 ошибке:

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

    Источник

    Problem

    Client PC is part of a workgroup and he is trying to use Office connection installed on a computer which is part of a domain. Cognos environment has SSO enabled and the end user is prompted for his login ( network login ) when he tries to connect to office connection. After putting credentials , office connection hangs and following error is displayed.

    Symptom

    The remote server returned an error: (401) Unauthorized

    System.Net.WebException : The remote server returned an error:( 401) Unauthorized.
    at Sytem.Net.HttpWebRequest.GetResponse()
    at Cognos.Office.Framework.Communication.DataSource.GetCAFContextId()
    at Cognos.Office.Framework.Communication.DataSource.Logon()
    at Cognos.Office.Framework.UI.Toolbars.UIToolbar.Logon(String Key)

    Cause

    Computer trying to connect to
    Office connection was part of workgroup

    Environment

    Windows, IIS 6.0

    Resolving The Problem

    Configure the computer to be part of same domian as Cognos server .

    Steps:1. First login to server where Cognos is installed , Right click on ‘My computer’ on dektop and click on ‘Properties’

    2. Click on ‘Computer Name’ tab and note the domain name ; ex: test.cognos.com

    3. Login to the computer having problem and open the ‘My computer’ properties, click on ‘computer name’ and it should display that computer is part of a workgroup.

    4. Click on ‘Change’ button, and choose ‘Domain’ and type the domian name retrieve from step 1-2 and click ok, close all the windows and restart your computer and make sure you choose the domain when logging on to windows.

    [{«Product»:{«code»:»SS9RUJ»,»label»:»Cognos 8 Go! Mobile»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Cognos 8 Go! Office»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»Cognos 8 Go! Office 8.2″,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

    Historical Number

    1038683

    We encountered below exception when we were integrating CRM with SharePoint.

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

    Environment details:

    • CRM 2016 on-premise with Claims authentication enabled.
    • SharePoint Server On-premise with Claims authentication enabled.
    • User Account using to set up is Admin on both the CRM and Sharepoint servers.

    Reason & Fix:

    Fix suggested in this MSDN Forum worked for us.

    It seems there is a known issue/bug with CRM 2016 that doesn’t allow this to work if you try using https in the MetadataEndPoint.

    To get this working, you will have to temporarily do the following items before running the SharePoint Power Shell command.

    Note : Make sure you note all the existing settings before executing below steps which helps you to roll back, if something goes wrong.

    Steps:

    1. Open the CRM Deployment Manager tool
      • Disable CRM IFD
      • Disable CRM Claims Configuration
    2. Open the IIS and remove the https binding on the CRM Web site and add back the http binding for the CRM Web site.
    3. Run CRM Deployment Manager and change the properties of the deployment for the Web Address to use http instead of https.
    4. Run an IISReset on the CRM Server to ensure this is now accessible via http.
    5. Run the SharePoint PowerShell commands (you should be able to access the MetadataEndpoint using http vs. https now if you put it in the browser (and it should prompt to download a .json file).
    6. Once the SharePoint commands are finished running, you need to reverse the changes above in CRM to re-enable IFD.
    7. Change the CRM Web Address to use https in the CRM Deployment Properties.
    8. Remove the http binding on the CRM Web site and add back the https binding, selecting the correct SSL Certificate.
    9. Run the Configure CRM Claims in the CRM Deployment Manager.  (keep the existing settings)
    10. Run the Configure IFD in the CRM Deployment Manager (keep existing settings).
    11. Run an IISReset on the CRM Server.

    Refer MSDN article  which details integrating SharePoint on-premise with CRM on-premise.

    🙂

    Понравилась статья? Поделить с друзьями:
  • System net http httprequestexception an error occurred while sending the request
  • System launcher ошибка загрузки xiaomi
  • System language adaptation fail access denied как исправить
  • System information was not obtained because of msinfo32 execution error перевод
  • System indexoutofrangeexception как исправить