мой ASP.NET v3.5 веб-приложение создает следующее исключение при попытке открыть соединение с базой данных SQL Server 2008:
система.Данные.В sqlclient.Sqlexception в:
Не удается открыть базу данных «MyDbName»
запрошено логином. Вход
неудачный. Ошибка входа для пользователя ‘ NT
ОРГАН ЗАПИСИ IUSR’.
дело в том, что я добавил NT AUTHORITYIUSR в список логинов сервера и в список пользователей базы данных. Для сервера, я предоставил пользователю публичную роль, а для базы данных я предоставил db_datareader разрешения.
Я также предоставил то же самое для NT AUTHORITYNETWORK SERVICE, под которым выполняется пул приложений.
веб-приложение размещается в IIS7, если это имеет значение. Проблема повторяется, когда БД и IIS находятся на одной физической машине.
7 ответов
фокус здесь в том, что NT AUTHORITYNETWORK SERVICE фактически отображается в базе данных как DOMAINNAMEMACHINENAME$ (обратите внимание на $ знак!). То есть, когда вы пересекаете границу машины с вашего веб-сервера на SQL Server, SQL Server видит учетную запись машины, если вы используете NETWORK SERVICE или LOCAL SYSTEM учетные записи. Если вы используете любую другую учетную запись, не являющуюся доменной, SQL Server не получит ваши учетные данные.
Я немного озадачен вашим сообщением об ошибке. По правде говоря, я не думаю, что когда DB находится на другой коробке, вы увидите все, кроме Login Failed for NT AUTHORITYANONYMOUS LOGON.
IUSR используется для анонимных веб-сайтов и не может пройти по проводу к SQL Server. Вы можете найти способ, чтобы это сработало, если вы делаете все на одной машине, но я никогда не узнаю, потому что я никогда не буду делать это таким образом… 😉
Я бы предложил создать отдельную (желательно доменную) учетную запись и указать ее в строке подключения (обычно в интернете.конфиг)
Затем вы можете ограничить разрешения на веб-сервере, что эта учетная запись может и не может делать.
Затем вы можете предоставить этой учетной записи необходимые разрешения в SQL server.
У меня была такая же проблема, и я решил ее, изменив пул приложений.
1
автор: Roman Ostashevskyi
в случае, если это кому-то помогает, в интернете.config я добавил для этой ошибки, чтобы уйти (в разделе )
вместо Integrated Security=True; в строке подключения, просто используйте имя пользователя и пароль user=sa; pwd=mypassword;
простое решение-проверить свою сеть.файл config и убедитесь, что один из них является частью строки подключения к БД:
доверенное соединение=false
или
Интегрированная Безопасность=True
эта проблема отображается при восстановлении новой базы данных в последней базе данных.
чтобы решить эту проблему, вы должны перейти к sqlserver, затем security, а затем снова установить apppool.
- Remove From My Forums
-
Question
-
hello everyone,
i work with custom web part on VS2010 … and SQL 2008 R2 database when i add the web part in my page on sharepoint it keeps gave me this exception about login failed to this user ‘NT AUTHORITYIUSR’ ???
Server Error in ‘/’ Application.
———————————————————————————Login failed for user ‘NT AUTHORITYIUSR’.
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.Data.SqlClient.SqlException: Login failed for user ‘NT AUTHORITYIUSR’.
Answers
-
-
Marked as answer by
Wednesday, April 18, 2012 2:39 PM
-
Marked as answer by
-
-
Marked as answer by
Margriet Bruggeman
Wednesday, April 18, 2012 2:40 PM
-
Marked as answer by
- Remove From My Forums
-
Question
-
hello everyone,
i work with custom web part on VS2010 … and SQL 2008 R2 database when i add the web part in my page on sharepoint it keeps gave me this exception about login failed to this user ‘NT AUTHORITYIUSR’ ???
Server Error in ‘/’ Application.
———————————————————————————Login failed for user ‘NT AUTHORITYIUSR’.
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.Data.SqlClient.SqlException: Login failed for user ‘NT AUTHORITYIUSR’.
Answers
-
-
Marked as answer by
Wednesday, April 18, 2012 2:39 PM
-
Marked as answer by
-
-
Marked as answer by
Margriet Bruggeman
Wednesday, April 18, 2012 2:40 PM
-
Marked as answer by
It’s important to note that you’ll get this error, as I just did, if you don’t have IIS configured to allow impersonation, but you do have your web.config attempting to do impersonation.
I just came across this exact error, and all of the following steps are required:
-
Ensure ASP.NET impersonation is enabled on your IIS web server:

-
Combine that with configuring your site to use impersonation (web.config):
<system.web> <identity impersonate="true" userName="your_service_acct" password="***" /> </system.web> -
The above steps presume that you have a SQL Login setup on your MSSQL for ‘your_service_acct’ with permissions
When running on localhost, against a localdb, or even a remote db that you personally have permissions on, the development IIS runs as if it were YOU — and everything just magically works. So, in debug mode, you don’t need to create a special web.config..
As soon as you deploy your site onto some kind of server (in my case, our TEST environment) you’ll likely need to have done the above steps I just detailed, because IIS will try to connect as the application pool user, which is not usually what you want administratively speaking. So, that’s when you want to start using web.config transformations, so Visual Studio will insert the appropriate identity impersonate="true" during your ‘Publish…’ deployment step.
Важно отметить, что вы получите эту ошибку, как и я, если у вас не настроен IIS для разрешения олицетворения, но ваш web.config пытается выполнить олицетворение.
Я только что столкнулся с этой точной ошибкой, и требуются все следующие шаги (но я пропустил первый шаг:
1.) Убедитесь, что олицетворение ASP.NET включено на вашем веб-сервере IIS:
2.) Объедините это с настройкой вашего сайта для использования олицетворения (web.config):
<system.web>
<identity impersonate="true" userName="your_service_acct" password="***" />
3.) Приведенные выше шаги предполагают, что у вас есть настройка входа в SQL на вашем MSSQL для «your_service_acct» с разрешениями.
При работе на локальном хосте, на локальной базе данных или даже на удаленной базе данных, на которую у вас есть разрешения, IIS для разработки работает так, как если бы это были ВЫ, и все работает просто волшебным образом. Таким образом, в режиме отладки вам не нужно создавать специальный файл web.config.
Как только вы развернете свой сайт на каком-либо сервере (в моем случае, в нашей среде TEST), вам, вероятно, потребуется выполнить описанные выше шаги, которые я только что описал, потому что IIS попытается подключиться как пользователь пула приложений, который обычно не то, что вы хотите с административной точки зрения. Итак, вот когда вы хотите начать использовать преобразования web.config, поэтому Visual Studio вставит соответствующий identity impersonate="true" на этапе развертывания «Опубликовать…».
- Remove From My Forums
-
Question
-
Hi,
I’ve created my custom database MyDatabase on the same server as SharePoint. When I try to access the database from a SharePoint page (a custom Master Page OnLoad event) I get the following error:
Cannot open database «MyDatabase» requested by the login. The login failed.
Login failed for user ‘NT AUTHORITYIUSR’.I’ve been looking for the IUSR user all around the server (SQL Server, IIS, Users and Groups etc) and I can’t find such an account. Could anybody explain me how to fix this problem and get access to my custom database?
Thanks,
Leszek
Answers
-
Thanks, this is what I did. I’m using a special account to access my database.
Leszek
-
Marked as answer by
Wednesday, June 29, 2011 2:26 PM
-
Marked as answer by
Premise
This was the error I got while trying to directly connect to a SQL Server database, from within a SharePoint web part, using the option, Windows Authentication.
Login failed for user ‘NT AuthorityIUSR’
Solution
The solution is to allow login for IUSR. Here are the steps to do it: –
1) Open Microsoft SQL Server Management Studio.
2) Under Security, right click the Logins leaf and select New Login.
3) In the Login Name, type in IUSR and hit the Search button.
4) This will open up a new window. Here also, type in IUSR in the object name and then, click on Check Names. Once, it has searched the name, click OK to close the window.
5) By default, you’ll be shown the name in the format, [machineName]IUSR. For example, in the following case, SERVERPIYUSH is my [machineName].
6) Change the [machineName] to NT Authority. So now, the Login name will look like this, NT AuthorityIUSR
7) Now, select Server Roles from the top-left navigation pane and assign the role, sysadmin. Now, this totally depends upon your requirement. In my case, I needed this permission. If you don’t need the highest privilege then go for the ones that serve your purpose. By default, the role, public will be applied to it.
8) Hit the OK button.
After allowing access to IUSR, I was now able to successfully connect to my SQL Server database using Windows Authentication through my code.
Key Takeaways
- NT Authority, refers to the OS itself. It means that the OS will authorize some stuffs on your behalf.
- Similarly, IUSR is nothing but a legacy account for allowing anonymous access. So, in totality, we can say, that NT AuthorityIUSR means that OS will grant anonymous access on my behalf with the roles I have explicitly specified for it.