In my previous post, you learned how to troubleshoot HTTP Error 503. Today, we will look into how to troubleshoot 401 – Unauthorized: Access is denied due to invalid credentials in Internet Information Services (IIS).
Contents
- 401 – Unauthorized
- How IIS authentication works
- Cause of error
- Debugging the error
- Resolving the error
- Common 401 substatus codes
- Conclusion
- Author
- Recent Posts
Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows Servers, Active Directory, PowerShell, web servers, networking, Linux, virtualization, and penetration testing. He loves writing for his blog.
401 – Unauthorized
401 Unauthorized Access is denied due to invalid credentials
The 401 – Unauthorized: Access is denied due to invalid credentials error is a common access-related error that you may experience with a website hosted on IIS.
How IIS authentication works
The error itself indicates that it is caused by a failure to authorize access. Someone who is a beginner in IIS could find the error description «you do not have permission to view this directory or page using the credentials that you supplied» slightly confusing. If you think from an end user’s perspective, you might be wondering when you supplied any credentials while accessing the website. Well, this happened automatically on the server side. By default, every website hosted on IIS has anonymous authentication enabled.
If you open the IIS Manager, select your website, and then double-click Authentication under the IIS section in the Features view, you will see the various authentication modes (such as basic authentication, forms authentication, anonymous authentication, etc.) that are supported by IIS.
Viewing various authentication modes supported by a website in IIS
Each website has to have at least one authentication mode enabled and, by default, Anonymous Authentication mode enabled. Authentication is a mechanism that is used to verify the visitor’s identity to your website. See the following screenshot for reference:
Default authentication modes supported by a website in IIS
Anonymous authentication allows visitors to access the public content of your website anonymously without having to supply any credentials. If you don’t want to use it, select the authentication mode, and then click Disable in the Actions pane on the right. To view or modify which credentials are used by anonymous authentication, click the Edit link on the right. You will see two options, as shown in the following screenshot:
View or modify the credentials used by anonymous authentication in IIS
By default, each website is set to use the IUSR user for anonymous user identity, which is a built-in account starting with IIS version 7. If you are using a custom username as the application pool identity, make sure you select the application pool identity option here. This way, you don’t have to worry about updating the user’s password in the website configuration over and over when the user’s password is changed.
Cause of error
The primary cause of the 401 – Unauthorized: Access is denied due to invalid credentials error is that you are using a custom username as the application pool identity. In simple terms, when you set the application pool to use a custom application pool identity (a custom username and password) rather than the default identity (which is ApplicationPoolIdentity), the Anonymous Authentication mode of the website continues using the IUSR user for authentication, which results in this error.
Debugging the error
As discussed in previous posts, the error page we saw above is a custom error page and does not reveal much helpful information for administrators. If you enable the detailed errors, you will see an error page with much detailed information, as shown in the following screenshot:
Error message 401.3 – You do not have permission to view this directory or page using the credentials you supplied (access denied due to Access Control Lists)
The detailed error gave you the HTTP 401.3 status code, which will guide you in checking the access control permissions on the file system. Make sure that the user who is set as the application pool identity has the read and execute permissions on the website’s root directory. If the error persists, the most likely cause is incorrect anonymous user identity. The following screenshot shows the problematic scenario:
Mismatched application pool identity and anonymous authentication identity user in IIS
The screenshot shows a mismatched application pool identity and anonymous authentication identity on the website, which is causing the error. For a website to work properly, both should be the same.
Resolving the error
Now that you know the cause of the HTTP 401.3 status code, do the following to fix the error:
If you are using a custom username as the application pool identity, make sure that the user has read and execute permissions on the website’s root directory.
Ensuring that the custom application pool user has read and execute permissions on the root directory
If you’re using the default ApplicationPoolIdentity for your application pool, make sure that the built-in IUSR user or IIS_IUSRS group has exactly the same permissions as shown in the screenshot below.
Ensuring that the default application pool identity has read and execute permissions on the root directory
If the error persists, edit the Anonymous Authentication setting of your website, as explained in the How IIS authentication works section. Be sure it is set to use the Application pool identity. See the following screenshot for reference:
Modifying the anonymous authentication identity to match the application pool identity in IIS
Common 401 substatus codes
The following table covers the most common HTTP 401 substatus codes, along with their possible causes and troubleshooting advice:
Subscribe to 4sysops newsletter!
Status Code | Possible Cause | Troubleshooting Advice |
401.1 | Logon failed | The logon attempt failed, probably due to an invalid user name or password. |
401.2 | Logon failed due to server configuration | The 401.2 status code indicates that there is a problem in the authentication configuration on the server. |
401.3 | Unauthorized due to ACL on resource | We covered how to fix this error above. |
Conclusion
I hope you’re enjoying this series of resolving common HTTP errors. In the next post, we will discuss how to fix the HTTP Error 403.14 – Forbidden error.
Дано: Windows Server 2012 R2
Ошибка: HTTP 401.1 — Unauthorized: Logon Failed при авторизации на сайте (IIS)
Для каких случаев данное решение:
- У Вас IIS версии 5.1 или выше
- Используется доменная аутентификация для сайта (Windows Authentication)
- Вы пытаетесь локально (на той же машине, где находится сам IIS) открыть сайт, у которого применена доменная авторизация
- Вы пытаетесь локально обратиться к сервисам на IIS по доменной авторизации (например, если на этом же сервере установлен кластер 1С, а в серверном коде производится попытка обратиться к сервисам на локальном IIS)
В этих случаях получаем примерно такое сообщение об ошибке:
HTTP Error 401.1 — Unauthorized
You do not have permission to view this directory or page using the credentials that you supplied.
…
Detailed Error Information:
Module WindowsAuthenticationModule
Notification AuthenticateRequest
Handler 1C Web-service Extension
Error Code 0xc000006d
Requested URL Тут проблемный URL
Physical Path c:inetpubwwwrootwshs
Logon Method Not yet determined
Logon User Not yet determined
В логах сервера также можно увидеть следующее сообщение:
An account failed to log on.
Subject:
Security ID: NULL SID
Account Name: —
Account Domain: —
Logon ID: 0x0
Logon Type: 3
Account For Which Logon Failed:
Security ID: NULL SID
Account Name: username
Account Domain: domainname
Failure Information:
Failure Reason: An Error occured during Logon.
Status: 0xC000006D
Sub Status: 0x0
Process Information:
Caller Process ID: 0x0
Caller Process Name: —
Network Information:
Workstation Name: SRV-PRG
Source Network Address: —
Source Port: —
Detailed Authentication Information:
Logon Process:
Authentication Package: NTLM
Transited Services: —
Package Name (NTLM only): —
Key Length: 0
Как вариант решения: в реестре необходимо указать хост, к которому Вы разрешаете подключаться при помощи доменной аутентификации.
Для этого находим в реестре следующую ветку:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
Создаем новый ключ:
— Тип — Multi-String Value
— Имя — BackConnectionHostNames
— В значениях ключа указать нужные адреса.
После настройки — перезагрузите IIS.
Если Вам понравилась статья, пожалуйста, поставьте лайк, сделайте репост или оставьте комментарий. Если у Вас есть какие-либо замечания, также пишите комментарии.
I’m getting this error when I try and access my website:-
HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.
Most likely causes:
• No authentication protocol (including anonymous) is selected in IIS.
• Only integrated authentication is enabled, and a client browser was used that does not support integrated authentication.
• Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.
• The Web server is not configured for anonymous access and a required authorization header was not received.
• The "configuration/system.webServer/authorization" configuration section may be explicitly denying the user access.
Things you can try:
• Verify the authentication setting for the resource and then try requesting the resource using that authentication method.
• Verify that the client browser supports Integrated authentication.
• Verify that the request is not going through a proxy when Integrated authentication is used.
• Verify that the user is not explicitly denied access in the "configuration/system.webServer/authorization" configuration section.
• Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here.
Detailed Error Information:
Module UrlAuthorizationModule
Notification AuthorizeRequest
Handler ExtensionlessUrlHandler-Integrated-4.0
Error Code 0x80070005
Physical Path D:Logs
Logon Method Anonymous
Logon User Anonymous
More Information:
This error occurs when the WWW-Authenticate header sent to the Web server is not supported by the server configuration. Check the authentication method for the resource, and verify which authentication method the client used. The error occurs when the authentication methods are different. To determine which type of authentication the client is using, check the authentication settings for the client.
View more information »
Microsoft Knowledge Base Articles:
• 907273
• 253667
I have to use Anonymous authentication only, can anyone help please?
Steve Smith
2,2342 gold badges17 silver badges22 bronze badges
asked May 16, 2016 at 3:18
2
This unbelievably vague question and answer actually led me to the proper solution for the specific problem of HTTP 401.2 Unauthorized against an Anonymous Authentication resource in IIS. The «Authorization Rules» element within IIS allows a explicit Allow/Deny entries, with an explicit option for «All Anonymous Users.» Specifying this solved an access problem I spent the better part of a day trying to resolve, and I thought I’d add the additional detail here.
answered Mar 23, 2017 at 18:21
David WDavid W
10.1k34 silver badges60 bronze badges
1
Bit late to the party but hope this helps someone else. This happened to me when I deployed a site to a brand new web server. The fix was to go into ‘Authorization Rules’ and create a new rule that allows ‘all users’. I did it on the server level so it will inherit to all sites moving forward. Otherwise if you do it on the site level, it manages it via the web.config, and I’m guessing that you lose the setting if you overwrite the web.config with a version that does not include the rule.
answered Apr 5 at 6:05
Ok, Finally i got solution to my problem.
‘Authorization Rules’ were not set up on system.
I setup required ‘Authorization Rules’ and able to browse site successfully.
answered May 16, 2016 at 4:52
SainiSaini
1131 gold badge2 silver badges5 bronze badges
2
Появление сообщения об ошибке 401 Unauthorized Error («отказ в доступе») при открытии страницы сайта означает неверную авторизацию или аутентификацию пользователя на стороне сервера при обращении к определенному url-адресу. Чаще всего она возникает при ошибочном вводе имени и/или пароля посетителем ресурса при входе в свой аккаунт. Другой причиной являются неправильные настройки, допущенные при администрировании web-ресурса. Данная ошибка отображается в браузере в виде отдельной страницы с соответствующим описанием. Некоторые разработчики интернет-ресурсов, в особенности крупных порталов, вводят собственную дополнительную кодировку данного сбоя:
- 401 Unauthorized;
- Authorization Required;
- HTTP Error 401 – Ошибка авторизации.
Попробуем разобраться с наиболее распространенными причинами возникновения данной ошибки кода HTTP-соединения и обсудим способы их решения.
Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя
При доступе к некоторым сайтам (или отдельным страницам этих сайтов), посетитель должен пройти определенные этапы получения прав:
- Идентификация – получение вашей учетной записи («identity») по username/login или email.
- Аутентификация («authentic») – проверка того, что вы знаете пароль от этой учетной записи.
- Авторизация – проверка вашей роли (статуса) в системе и решение о предоставлении доступа к запрошенной странице или ресурсу на определенных условиях.
Большинство пользователей сохраняют свои данные по умолчанию в истории браузеров, что позволяет быстро идентифицироваться на наиболее часто посещаемых страницах и синхронизировать настройки между устройствами. Данный способ удобен для серфинга в интернете, но может привести к проблемам с безопасностью доступа к конфиденциальной информации. При наличии большого количества авторизованных регистрационных данных к различным сайтам используйте надежный мастер-пароль, который закрывает доступ к сохраненной в браузере информации.
Наиболее распространенной причиной появления ошибки с кодом 401 для рядового пользователя является ввод неверных данных при посещении определенного ресурса. В этом и других случаях нужно попробовать сделать следующее:
- Проверьте в адресной строке правильность написания URL. Особенно это касается перехода на подстраницы сайта, требующие авторизации. Введите правильный адрес. Если переход на страницу осуществлялся после входа в аккаунт, разлогинитесь, вернитесь на главную страницу и произведите повторный вход с правильными учетными данными.
- При осуществлении входа с сохраненными данными пользователя и появлении ошибки сервера 401 проверьте их корректность в соответствующих настройках данного браузера. Возможно, авторизационные данные были вами изменены в другом браузере. Также можно очистить кэш, удалить cookies и повторить попытку входа. При удалении истории браузера или очистке кэша потребуется ручное введение логина и пароля для получения доступа. Если вы не помните пароль, пройдите процедуру восстановления, следуя инструкциям.
- Если вы считаете, что вводите правильные регистрационные данные, но не можете получить доступ к сайту, обратитесь к администратору ресурса. В этом случае лучше всего сделать скриншот проблемной страницы.
- Иногда блокировка происходит на стороне провайдера, что тоже приводит к отказу в доступе и появлению сообщения с кодировкой 401. Для проверки можно попробовать авторизоваться на том же ресурсе с альтернативного ip-адреса (например, используя VPN). При подтверждении блокировки трафика свяжитесь с провайдером и следуйте его инструкциям.
Некоторые крупные интернет-ресурсы с большим количеством подписчиков используют дополнительные настройки для обеспечения безопасности доступа. К примеру, ваш аккаунт может быть заблокирован при многократных попытках неудачной авторизации. Слишком частые попытки законнектиться могут быть восприняты как действия бота. В этом случае вы увидите соответствующее сообщение, но можете быть просто переадресованы на страницу с кодом 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-кода с привлечением разработчика сайта.
- Remove From My Forums
-
Question
-
User1377211471 posted
I am getting the below error message in my windows 2008 server when I am trying to browse the default website in the local server. Anonymous auth is disabled. Windows auth is enabled.
Error Summary
HTTP Error 401.2 — Unauthorized
You are not authorized to view this page due to invalid authentication headers.
<FIELDSET><LEGEND>Detailed Error Information</LEGEND>
Module IIS Web Core Notification AuthenticateRequest Handler StaticFile Error Code 0x80070005 Requested URL http://localhost:80/ Physical Path C:inetpubwwwroot Logon Method Not yet determined Logon User Not yet determined Failed Request Tracing Log Directory C:inetpublogsFailedReqLogFiles </FIELDSET>
<FIELDSET><LEGEND>Most likely causes:</LEGEND>
- No authentication protocol (including anonymous) is selected in IIS.
- Only integrated authentication is enabled, and a client browser was used that does not support integrated authentication.
- Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.
- The Web server is not configured for anonymous access and a required authorization header was not received.
- The «configuration/system.webServer/authorization» configuration section may be explicitly denying the user access.
</FIELDSET>
<FIELDSET><LEGEND>Things you can try:</LEGEND>
- Verify the authentication setting for the resource and then try requesting the resource using that authentication method.
- Verify that the client browser supports Integrated authentication.
- Verify that the request is not going through a proxy when Integrated authentication is used.
- Verify that the user is not explicitly denied access in the «configuration/system.webServer/authorization» configuration section.
- Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click
here.
</FIELDSET>
<FIELDSET><LEGEND>Links and More Information</LEGEND>This error occurs when the WWW-Authenticate header sent to the Web server is not supported by the server configuration. Check the authentication method for the resource, and
verify which authentication method the client used. The error occurs when the authentication methods are different. To determine which type of authentication the client is using, check the authentication settings for the client.View more information »
Microsoft Knowledge Base Articles:
</FIELDSET>
Ther are no webproxy, IE7 is enable for local intranet connection.