Сеанс ошибка аутентификации nt authority система

мой 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
      Margriet Bruggeman
      Wednesday, April 18, 2012 2:40 PM
  • 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
      Margriet Bruggeman
      Wednesday, April 18, 2012 2:40 PM

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:

  1. Ensure ASP.NET impersonation is enabled on your IIS web server:enter image description here

  2. Combine that with configuring your site to use impersonation (web.config):

    <system.web>
        <identity impersonate="true" userName="your_service_acct" password="***" />
    </system.web>
    
  3. 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

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].

Adding Default Windows Authentication to SQL Server

6) Change the [machineName] to NT Authority. So now, the Login name will look like this, NT AuthorityIUSR

Adding NT Authority Windows Authentication to SQL Server

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.

Adding sysadmin role to SQL Server login

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.

лог iss:

1. в обоих случаях идет несколько запросов get со статусом 200, затем запрос post со статусом 402 (странно)

2.  случая открытия с сервера дальше идет запрос post (200) еще несколько запросов get со статусом 200, а в случае обращения с клиентской машины, этих дальнейших запросов нет. Получается это клиентская машина не посылает запросы почему то? Но я пробовал с разных машин и с разных браузеров, каспера отключал.

в пофигураторе, в окошке публикации базы, стоит галка «использовать аутентификацию операционной системы», в IIS в «Проверке подлности» стоит «Проверка подлинности windows» включена

Если бы фаерволы рубили соединения не было бы ответов в логах.

I been strugling with this for 2 days now without comming any closer to solution. I have read 20-30 threads alteast and stil can not resolve this.

Please help me out.

I have disable anonymous authentication, enable asp.net impersonation.

I have added <identity impersonate = "true" />

I have added the a user to the security logins that is connected to the database I try to connect to

This is the connectionstring I use:

Data Source=IPTOSERVER;Initial Catalog=Phaeton;User Id=User;Password=Password;

errormessage:

Cannot open database «Phaeton.mdf» requested by the login. The login failed.

Login failed for user ‘NT AUTHORITYNETWORK SERVICE’.

Lucero's user avatar

Lucero

58.9k9 gold badges122 silver badges151 bronze badges

asked Feb 12, 2010 at 12:47

Dejan.S's user avatar

5

I was experiencing a similar error message that I noticed in the Windows Event Viewer that read:

Login failed for user ‘NT AUTHORITYNETWORK SERVICE’. Reason: Failed to open the explicitly specified database. [CLIENT: local machine]

The solution that resolved my problem was:

  1. Login to SqlExpress via SQL Server Management Studio
  2. Go to the «Security» directory of the database
  3. Right-click the Users directory
  4. Select «New User…»
  5. Add ‘NT AUTHORITYNETWORK SERVICE’ as a new user
  6. In the Data Role Membership area, select db_owner
  7. Click OK

Here’s a screenshot of the above:
Screenshot of adding new user Network Service as db_owner to SqlExpress

David Murdoch's user avatar

David Murdoch

87.4k39 gold badges147 silver badges191 bronze badges

answered Sep 9, 2010 at 16:21

Jed's user avatar

JedJed

10.5k19 gold badges81 silver badges124 bronze badges

6

The error message you are receiving is telling you that the application failed to connect to the sqlexpress db, and not sql server.
I will just change the name of the db in sql server and then update the connectionstring accordingly and try it again.

Your error message states the following:

Cannot open database "Phaeton.mdf" requested by the login. The login failed.

It looks to me you are still trying to connect to the file based database, the name «Phaeton.mdf» does not match with your new sql database name «Phaeton».

Hope this helps.

answered Feb 12, 2010 at 16:11

Ricardo Sanchez's user avatar

Ricardo SanchezRicardo Sanchez

6,0593 gold badges24 silver badges31 bronze badges

1

If the error message is just

«Login failed for user ‘NT AUTHORITYNETWORK SERVICE’.», then grant
the login permission for ‘NT AUTHORITYNETWORK SERVICE’

by using

"sp_grantlogin 'NT AUTHORITYNETWORK SERVICE'" 

else if the error message is like

«Cannot open database «Phaeton.mdf» requested by the login. The login
failed. Login failed for user ‘NT AUTHORITYNETWORK SERVICE’.»

try using

"EXEC sp_grantdbaccess 'NT AUTHORITYNETWORK SERVICE'" 

under your «Phaeton» database.

Dgan's user avatar

Dgan

10k1 gold badge29 silver badges51 bronze badges

answered Jun 8, 2012 at 14:39

Santosh's user avatar

SantoshSantosh

811 silver badge1 bronze badge

0

I liked Jed’s solution but the issue with that was every time I built my project in debug mode, it would deploy my database project and removed the user again. so I added this MySQL script to the Post-Deployment script.
it practically does what Jed said but creates the user every time I deploy.

CREATE USER [NT AUTHORITYNETWORK SERVICE]
    FOR LOGIN [NT AUTHORITYNETWORK SERVICE]
    WITH DEFAULT_SCHEMA = dbo;
Go

EXEC sp_addrolemember 'db_owner', 'NT AUTHORITYNETWORK SERVICE'

answered May 18, 2012 at 19:04

Ida N's user avatar

Ida NIda N

1,88122 silver badges21 bronze badges

1

You said it worked fine when you were using SQL Express edition. By default express editions create a named instance & run in NT AuthorityNetwork Service.

SQL Server STD by default install a default instance & run in NT AuthoritySYSTEM.

Do you have both the full SQL edition & Express edition installed on the same machine?

  1. It could be that somewhere the connection string still refers to the Named instance ‘SQLEXPRESS’ rather than the default instance created by the full version.

  2. Also where is the connection string defined? In IIS or your code? Make sure that if defined in many places, all point to same SQL instance & database.

  3. Also try looking at the detailed error present in the SQL Server error logs. The error logged in event log are not complete for secuirty reasons. This will also help you to know if the connection was made to the correct SQL Server.

  4. Also make sure that the machine on which SQL is installed is accessible & IIS is trying to access the same machine. In my company sometimes due to wrong name resolution, the query fails since most of our computers have SQL installed & the query lands in the wrong SQL Server.

  5. Make sure that the database exists in the SQL Server. The name displayed under databases in SQL Management Studio should match that in the connection string.

answered Feb 12, 2010 at 13:12

Ganesh R.'s user avatar

Ganesh R.Ganesh R.

4,3373 gold badges28 silver badges46 bronze badges

1

The SQL Server login required is DOMAINmachinename$. This is the how the calling NT AUTHORITYNETWORK SERVICE appears to SQL Server (and file servers etc)

In SQL,

CREATE LOGIN [XYZGandalf$] FROM WINDOWS

answered Feb 12, 2010 at 12:51

gbn's user avatar

gbngbn

420k81 gold badges585 silver badges674 bronze badges

1

The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use ‘NT AUTHORITYNETWORK SERVICE’ as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.

answered Apr 20, 2013 at 20:27

Vuyiswa Maseko's user avatar

I am using Entity Framework to repupulate my database, and the users gets overridden each time I generate my database.

Now I run this each time I load a new DBContext:

cnt.Database.ExecuteSqlCommand("EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\NETWORK SERVICE'");

answered Oct 13, 2014 at 10:21

Kenneth Bo Christensen's user avatar

Make sure that the database is created. I got the same error when I applied the migration to the wrong project in the solution. When I applied the migration to the right project, it created the database and that solved the error.

answered Sep 25, 2020 at 8:50

Ranj's user avatar

RanjRanj

6981 gold badge12 silver badges19 bronze badges

В моем веб-приложении ASP.NET v3.5 возникает следующее исключение, когда он пытается открыть соединение с базой данных SQL Server 2008:

System.Data.SqlClient.SqlException: Не удается открыть базу данных «MyDbName» запрошенный логином. Вход не смогли. Ошибка входа для пользователя NT AUTHORITYIUSR».

Дело в том, что я добавил NT AUTHORITYIUSR в список серверов для входа в систему и список пользователей в базе данных. Для сервера я предоставил пользователю роль Public, а для базы данных я предоставил разрешения db_datareader.

Я также предоставил то же самое для NT AUTHORITYNETWORK SERVICE, который является идентификатором, с которым работает пул приложений.

Веб-приложение размещено в IIS7, если это имеет значение. Проблема повторяется, когда DB и IIS находятся на одной и той же физической машине.

4b9b3361

Ответ 1

Фокус в том, что NT AUTHORITYNETWORK SERVICE фактически появляется в базе данных как DOMAINNAMEMACHINENAME$ (обратите внимание на знак $!). То есть, когда вы переходите границу машины с вашего веб-сервера на SQL Server, SQL Server видит учетную запись компьютера, если вы используете учетные записи NETWORK SERVICE или LOCAL SYSTEM. Если вы используете любую другую учетную запись, отличную от домена, SQL Server не получит ваши учетные данные.

Я немного озадачен вашим сообщением об ошибке. По правде говоря, я не думаю, что когда БД находится в другом окне, вы увидите что-нибудь кроме Login Failed for NT AUTHORITYANONYMOUS LOGON.

IUSR используется для анонимных веб-сайтов и не может передавать провод на SQL Server. Вы можете найти способ работать, если вы делаете все на одной машине, но я никогда не узнаю, потому что я никогда не буду так делать…; -)

Ответ 2

Я бы предложил создать отдельную (желательно доменную) учетную запись и указать ее в строке подключения (обычно в web.config)
Затем вы можете ограничить разрешения на веб-сервере, что эта учетная запись может и не может сделать.
Затем вы можете предоставить этой учетной записи необходимые разрешения на сервере SQL.

Ответ 3

У меня была такая же проблема и я решил эту проблему, изменив пул приложений.

Ответ 4

В случае, если это помогает кому-то, в web.config я добавил < identity impersonate = «false» /» > , чтобы эта ошибка ушла (под < system. web > )

Ответ 5

Вместо использования Integrated Security=True; в строке подключения просто используйте аутентификацию имени пользователя и пароля user=sa; pwd=mypassword;

Ответ 6

Простое решение — проверить файл web.config и убедиться, что один из них является частью строки подключения db:

Доверенное соединение = false

ИЛИ

Интегрированная безопасность = True

Ответ 7

Эта проблема отображается при восстановлении новой базы данных в вашей последней базе данных.

Чтобы решить эту проблему, вы должны перейти в sqlserver, затем в систему безопасности, а затем снова установить свой Apppool.

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:

  1. Ensure ASP.NET impersonation is enabled on your IIS web server:enter image description here

  2. Combine that with configuring your site to use impersonation (web.config):

    <system.web>
        <identity impersonate="true" userName="your_service_acct" password="***" />
    </system.web>
    
  3. 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.

Понравилась статья? Поделить с друзьями:
  • Се 348780 ошибка на приставке пс4
  • Сдэк ошибка сервера
  • Сдэк ошибка 503
  • Сдэк ошибка 502
  • Секретный шпион лексическая ошибка или нет