Ошибка access is denied due to invalid credentials

Появление сообщения об ошибке 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-кода с привлечением разработчика сайта. 

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

  1. 401 – Unauthorized
  2. How IIS authentication works
  3. Cause of error
  4. Debugging the error
  5. Resolving the error
  6. Common 401 substatus codes
  7. 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.

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

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

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

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

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 (acc

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

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

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

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

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.

I am using IIS Express to deploy MVC4 application. This website runs perfectly on same computer. But in Lan it gives me error 401.

<authentication mode="Forms">
    <forms loginUrl="~/" slidingExpiration="true" timeout="20">
    </forms>
</authentication>

In home controller

[HttpPost]
[AllowAnonymous]        
public ActionResult Index(LoginModel model, string returnUrl)
{
}

I am starting IIS server from command prompt in Administrator mode. IIS responds to the request with error 401.

Any clue?

Rahul Nikate's user avatar

Rahul Nikate

6,1625 gold badges41 silver badges54 bronze badges

asked Nov 7, 2012 at 22:45

java.manish.2015's user avatar

I realize this is an older post but I had the same error on IIS 8.5. Hopefully this can help another experiencing the same issue (I didn’t see my issue outlined in other questions with a similar title).

Everything seemed set up correctly with the Application Pool Identity, but I continued to receive the error. After much digging, there is a setting for the anonymous user to use the credentials of the application pool identity or a specific user. For whatever reason, mine was defaulted to a specific user. Altering the setting to the App Pool Identity fixed the issue for me.

  1. IIS Manager → Sites → Website
  2. Double click «Authentication»
  3. Select Anonymous Authentication
  4. From the Actions panel, select Edit
  5. Select Application pool Identity and click ok

Hopefully this saves someone else some time!

Uwe Keim's user avatar

Uwe Keim

39.3k56 gold badges174 silver badges291 bronze badges

answered Mar 3, 2015 at 16:31

ctc's user avatar

12

If you’re using IIS 7 do something like this:

  1. Select your site.
  2. Click on error pages.
  3. Edit feature settings.
  4. Select detailed errors.

Leandro Bardelli's user avatar

answered Dec 5, 2012 at 6:10

Suraj Shrestha's user avatar

Suraj ShresthaSuraj Shrestha

1,7901 gold badge24 silver badges50 bronze badges

3

Make sure that you enabled anonymous authentication on iis like this:

enter image description here

answered Nov 8, 2012 at 7:19

testCoder's user avatar

testCodertestCoder

7,10513 gold badges55 silver badges75 bronze badges

1

In case anyone is still looking for this, this solved the problem for us:

To whoever this may help, this saved my life…

IIS 7 was difficult for figuring out why i was getting the 401 — Unauthorized: Access is denied due to invalid credentials… until i did this…

  1. Open IIS and select the website that is causing the 401
  2. Open the «Authentication» property under the «IIS» header
  3. Click the «Windows Authentication» item and click «Providers»
  4. For me the issue was that Negotiate was above NTLM. I assume that there was some kind of handshake going on behind the scenes, but i was never really authenticated. I moved the NTLM to the top most spot, and BAM that fixed it.

Here is the link where this was found.

Uwe Keim's user avatar

Uwe Keim

39.3k56 gold badges174 silver badges291 bronze badges

answered Apr 23, 2014 at 21:05

Steve's user avatar

SteveSteve

5315 silver badges16 bronze badges

I had this issue on IIS 10. This is how I fixed it.

  1. Open IIS
  2. Select The Site
  3. Open Authentication
  4. Edit Anonymous Authentication
  5. Select Application Pool Identity

answered Dec 16, 2020 at 18:49

greenlight247's user avatar

2

I realize its an old question, but this came up in my searches. Had a similar issue for an MVC application recently built, deployed for the first time, and Authentication mechanism wasn’t completely hashed out.

It wasn’t an IIS setting in my case, it was a Controller that was not [AllowAnonymous] decorated. I was using a Render.Action/Html.Action in a Layout.cshtml and the User was unauthenticated. So the Layout tried to load an Authenticated Action in an UnAuthenticated context.

Once I updated the action to AllowAnonymous, the problem went away, and this is what led me to it.

Hope this helps someone.

Community's user avatar

answered Aug 5, 2014 at 16:14

poorraj's user avatar

poorrajpoorraj

1533 silver badges9 bronze badges

I faced this error when I created an empty project with the MVC folders and then deployed the application to the server. My issue was that I didn’t define the authentication in Web.config, so all I had to do was add this line to a system.web tag.

<system.web>
    <authentication mode="None"/>
</system.web>

answered Jul 31, 2017 at 14:32

Chris Gong's user avatar

Chris GongChris Gong

7,9864 gold badges30 silver badges51 bronze badges

I faced similar issue.

The folder was shared and Authenticated Users permission was provided, which solved my issue.

answered Aug 31, 2015 at 9:31

Jishnu's user avatar

0

I had a similar issue today. For some reason, my GET request was fine, but PUT request was failing for my WCF WebHttp Service

Adding the following to the Web.config solved the issue

 <system.web>
  <authentication mode="Forms" />
 </system.web>

answered Jun 13, 2017 at 20:21

Vijay Vepakomma's user avatar

i faced the same issue under IIS 8.5. A working solution for me was changing the IIS to display detailled errors. See answer from sna2stha. But i think it is not a good idea to forward detailed error messages to browsers in production enviroments.
I added/changed the existingResponse attribute in the httpErrors-Section, so the IIS not handled any extisting Asp.net Response:

<system.webServer>
   <httpErrors existingResponse="PassThrough" />
</system.webServer>

This works for me.

redcalx's user avatar

redcalx

8,1074 gold badges56 silver badges103 bronze badges

answered Nov 17, 2016 at 8:33

Saftpresse99's user avatar

In my case, what made it work was changing the Anonymous User identity from Specific user (IUSR) to Application Pool Identity. Weird enought because other sites are using the specific user IUSR and work fine.

answered Jun 27, 2020 at 20:13

Guy's user avatar

GuyGuy

1,1729 silver badges21 bronze badges

As so many answers have demonstrated, the error might be caused by a variety of reasons. In my case it was connected to authorization rules: they were added much later after the application was deployed. This feature of IIS is turned on as a Windows component (World Wide Web Services->Security->URL Authorization).

This particular section inside web.config was to blame:

<system.webServer>
  <security>
    <authorization>
      <remove users="*" roles="" verbs="" />
      <add accessType="Deny" users="?" />
      <add accessType="Deny" users="user1,user2" />
      <add accessType="Allow" users="*" />
    </authorization>
  </security>
</system.webServer>

Thus the record for users="?" blocked access to a path with anonymous authentication too since it inherited the rules by default. However, in IIS you can go to a particular folder/file that should be accessed anonymously and choose Authorization Rules:

enter image description here

Here it’s possible to overwrite the rules locally by removing the old one and optionally adding the allowed rule instead to make it more explicit:

enter image description here

answered Apr 2, 2021 at 13:55

Oleg Safarov's user avatar

Oleg SafarovOleg Safarov

2,30513 silver badges19 bronze badges

Right click on the main directory where the project files are located.

Properties-> Security-> Edit-> Add-> type IIS_IUSRS and click on «Check Names» button.

The result will look like ComputerUsernameIIS_IUSRS

For example: DESKTOP-M0R6PVFIIS_IUSRS

and then click on «Ok» button.

enter image description here

Amirhossein Rahmati's user avatar

answered Jan 12, 2022 at 14:09

BurhanY's user avatar

I had a slightly different problem. The credential problem was for the underlying user running the application, not the user trying to login. One way to test this is to go to IIS Management -> Sites -> Your Site -> Basic Settings -> Test Settings.

answered Feb 28, 2020 at 0:11

Federico's user avatar

FedericoFederico

1,6062 gold badges22 silver badges24 bronze badges

I had a permissions issue to a website and just couldn’t get Windows authentication to work. It was a folder permissions rather than ASP.NET configuration issue in the end and once the Everyone user was granted permissions it started working.

answered Jan 14, 2020 at 10:10

SharpC's user avatar

SharpCSharpC

6,8464 gold badges45 silver badges40 bronze badges

You can press F4 on the web project to get the «Project Properties» window.

Then make sure Anonymous Authentication is Enabled in the «Development Server» section:

enter image description here

answered Nov 15, 2021 at 18:07

d.popov's user avatar

d.popovd.popov

4,1151 gold badge35 silver badges47 bronze badges

In my case,
My application is developed in MVC and my home controller class was decorated with [Authorize] which was causing this issue.
So I’ve removed it because my application don’t require any authentication.

answered Jan 31, 2018 at 14:02

Rahul Nikate's user avatar

Rahul NikateRahul Nikate

6,1625 gold badges41 silver badges54 bronze badges

Я использую IIS Express для развертывания приложения MVC4. Этот сайт отлично работает на одном компьютере. Но в Lan это дает мне ошибку 401.

<authentication mode="Forms">
    <forms loginUrl="~/" slidingExpiration="true" timeout="20">
    </forms>
</authentication>

В домашнем контроллере

[HttpPost]
[AllowAnonymous]        
public ActionResult Index(LoginModel model, string returnUrl)
{
}

Я запускаю сервер IIS из командной строки в режиме администратора. IIS отвечает на запрос с ошибкой 401.

Любая подсказка?

4b9b3361

Ответ 1

Я понимаю, что это более старая должность, но у меня была такая же ошибка в IIS 8.5. Надеюсь, это может помочь другому испытать ту же проблему (я не видел, чтобы моя проблема была изложена в других вопросах с похожим названием).

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

  • Менеджер IIS → Сайты → Веб-сайт
  • Дважды щелкните «Аутентификация»
  • Выберите анонимную аутентификацию
  • На панели «Действия» выберите «Редактировать»
  • Выберите идентификатор пула приложений и нажмите ok

Надеюсь, это поможет кому-то еще некоторое время!

Ответ 2

Если вы используете IIS 7, выполните следующие действия:

  • Выберите свой сайт.
  • Нажмите на страницы с ошибкой.
  • Изменить настройки параметров.
  • Выберите подробные ошибки.

Enjoy.

Ответ 3

Убедитесь, что вы включили анонимную аутентификацию в iis следующим образом:

enter image description here

Ответ 4

В случае, если кто-то все еще ищет это, это решило проблему для нас:

Кому бы это ни помогло, это спасло мою жизнь…

IIS 7 было сложно выяснить, почему я получаю 401 — Unauthorized: доступ запрещен из-за недействительных учетных данных… пока я не сделал это…

  • Откройте IIS и выберите веб-сайт, вызывающий 401
  • Откройте свойство «Аутентификация» в заголовке «IIS»
  • Нажмите «Аутентификация Windows» и нажмите «Поставщики»
  • Для меня проблема заключалась в том, что Negotiate был выше NTLM. Я предполагаю, что какое-то рукопожатие происходит за кулисами, но я никогда не был аутентифицирован. Я переместил NTLM на самое верхнее место, а BAM установил его.

Вот ссылка, где это было найдено.

Ответ 5

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

В моем случае это не было настройкой IIS, это был контроллер, который не был [AllowAnonymous] украшен. Я использовал Render.Action/Html.Action в Layout.cshtml, и Пользователь был не аутентифицирован. Таким образом, макет попытался загрузить аутентифицированное действие в контексте UnAuthenticated.

Как только я обновил действие до AllowAnonymous, проблема исчезла, и вот что привело меня к этому.

Надеюсь, это поможет кому-то.

Ответ 6

У меня была аналогичная проблема сегодня. По какой-то причине мой запрос GET был в порядке, но запрос PUT не выполнялся для моей службы WCF WebHttp Service

Добавление следующего в Web.config решения проблемы

 <system.web>
  <authentication mode="Forms" />
 </system.web>

Ответ 7

Я столкнулся с этой ошибкой, когда создал пустой проект с папками MVC, а затем развернул приложение на сервере. Моя проблема заключалась в том, что я не определял аутентификацию в Web.config, поэтому все, что мне нужно было сделать, это добавить эту строку в тег system.web.

<system.web>
    <authentication mode="None"/>
</system.web>

Ответ 8

У меня возникла аналогичная проблема.

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

Ответ 9

i столкнулся с той же проблемой в IIS 8.5. Рабочее решение для меня изменило IIS, чтобы отобразить подробные ошибки. См. Ответ от sna2stha. Но я думаю, что не рекомендуется отправлять подробные сообщения об ошибках в браузеры в производственных средах.
Я добавил/изменил существующий атрибутResponse в разделе httpErrors-Section, поэтому IIS не обработал любой из оставшихся ответов Asp.net:

 <httpErrors existingResponse="PassThrough" />

Это работает для меня.

You are here: Home / How To / How to Fix Access Denied (401) Error in Microsoft IIS

After migrating a web application to a new server, we encountered this server error:

401 - Unauthorized: Access is denied due to invalid credentials. You do not have permision to view this directory or page using the credentials that you supplied.

Server Error 401

Ответ 1

Я понимаю, что это более старая должность, но у меня была такая же ошибка в IIS 8.5. Надеюсь, это может помочь другому испытать ту же проблему (я не видел, чтобы моя проблема была изложена в других вопросах с похожим названием).

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

  • Менеджер IIS → Сайты → Веб-сайт
  • Дважды щелкните «Аутентификация»
  • Выберите анонимную аутентификацию
  • На панели «Действия» выберите «Редактировать»
  • Выберите идентификатор пула приложений и нажмите ok

Надеюсь, это поможет кому-то еще некоторое время!

Ответ 2

Если вы используете IIS 7, выполните следующие действия:

  • Выберите свой сайт.
  • Нажмите на страницы с ошибкой.
  • Изменить настройки параметров.
  • Выберите подробные ошибки.

Enjoy.

Ответ 3

Убедитесь, что вы включили анонимную аутентификацию в iis следующим образом:

enter image description here

Ответ 4

В случае, если кто-то все еще ищет это, это решило проблему для нас:

Кому бы это ни помогло, это спасло мою жизнь…

IIS 7 было сложно выяснить, почему я получаю 401 — Unauthorized: доступ запрещен из-за недействительных учетных данных… пока я не сделал это…

  • Откройте IIS и выберите веб-сайт, вызывающий 401
  • Откройте свойство «Аутентификация» в заголовке «IIS»
  • Нажмите «Аутентификация Windows» и нажмите «Поставщики»
  • Для меня проблема заключалась в том, что Negotiate был выше NTLM. Я предполагаю, что какое-то рукопожатие происходит за кулисами, но я никогда не был аутентифицирован. Я переместил NTLM на самое верхнее место, а BAM установил его.

Вот ссылка, где это было найдено.

Ответ 5

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

В моем случае это не было настройкой IIS, это был контроллер, который не был [AllowAnonymous] украшен. Я использовал Render.Action/Html.Action в Layout.cshtml, и Пользователь был не аутентифицирован. Таким образом, макет попытался загрузить аутентифицированное действие в контексте UnAuthenticated.

Как только я обновил действие до AllowAnonymous, проблема исчезла, и вот что привело меня к этому.

Надеюсь, это поможет кому-то.

Ответ 6

У меня была аналогичная проблема сегодня. По какой-то причине мой запрос GET был в порядке, но запрос PUT не выполнялся для моей службы WCF WebHttp Service

Добавление следующего в Web.config решения проблемы

 <system.web>
  <authentication mode="Forms" />
 </system.web>

Ответ 7

Я столкнулся с этой ошибкой, когда создал пустой проект с папками MVC, а затем развернул приложение на сервере. Моя проблема заключалась в том, что я не определял аутентификацию в Web.config, поэтому все, что мне нужно было сделать, это добавить эту строку в тег system.web.

<system.web>
    <authentication mode="None"/>
</system.web>

Ответ 8

У меня возникла аналогичная проблема.

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

Ответ 9

i столкнулся с той же проблемой в IIS 8.5. Рабочее решение для меня изменило IIS, чтобы отобразить подробные ошибки. См. Ответ от sna2stha. Но я думаю, что не рекомендуется отправлять подробные сообщения об ошибках в браузеры в производственных средах.
Я добавил/изменил существующий атрибутResponse в разделе httpErrors-Section, поэтому IIS не обработал любой из оставшихся ответов Asp.net:

 <httpErrors existingResponse="PassThrough" />

Это работает для меня.

You are here: Home / How To / How to Fix Access Denied (401) Error in Microsoft IIS

After migrating a web application to a new server, we encountered this server error:

401 - Unauthorized: Access is denied due to invalid credentials. You do not have permision to view this directory or page using the credentials that you supplied.

Server Error 401

This happened despite the fact the user is already authenticated via Active Directory.

There can be many causes to Access Denied error, but if you think you’ve already configured everything correctly from your ASP.NET application, there might be a little detail that’s forgotten. Make sure you give the proper permission to Authenticated Users to access your web application directory.

Right-click on the directory where the web application is stored and select Properties and click on Security tab.

Folder Properties - Security Tab

Click on Edit…, then Add… button. Type in Authenticated Users in the Enter the object names to select.

Adding Authenticated Users

Click OK and you should see Authenticated Users as one of the user names. Give proper permissions on the Permissions for Authenticated Users box on the lower end if they’re not checked already.

Security Permissions for Users

Click OK twice to close the dialog box. It should take effect immediately, but if you want to be sure, you can restart IIS for your web application.

Refresh your browser and it should display the web page now.

Further Reading

How to Use Custom 401 Error Page on IIS
How to Customize 401 Error Page with 302 Redirect on IIS
How to Install IIS on Windows
How to Solve Intermittent 403 Forbidden Access is Denied Error in IIS

Понравилась статья? Поделить с друзьями:
  • Ошибка access denied в браузере
  • Ошибка access denied to remote resource
  • Ошибка access denied for user localhost using password yes
  • Ошибка access denied for user localhost to database
  • Ошибка access control allow origin header is present