your programing

로그인에서 요청한 데이터베이스 "테스트"를 열 수 없습니다.

lovepro 2020. 10. 10. 10:46
반응형

로그인에서 요청한 데이터베이스 "테스트"를 열 수 없습니다. 로그인에 실패했습니다. 사용자 'xyz \ ASPNET'에 대한 로그인 실패


일부 데이터를 db에 저장하는 웹 서비스를 만들었습니다. 하지만이 오류가 발생합니다.

로그인에서 요청한 "테스트"데이터베이스를 열 수 없습니다. 로그인에 실패했습니다. 'xyz \ ASPNET'사용자가 로그인하지 못했습니다.

내 연결 문자열은

Data Source=.\SQLExpress;Initial Catalog=IFItest;Integrated Security=True

글쎄요, 그 오류는 아주 분명합니다. "xyz / ASPNET"사용자로 SQL Server에 연결하려고합니다.이 계정은 ASP.NET 앱이 실행되는 계정입니다.

이 계정은 SQL Server에 연결할 수 없습니다. 해당 계정에 대해 SQL Server에 로그인을 생성하거나 연결 문자열에 다른 유효한 SQL Server 계정을 지정하십시오.

원래 질문을 업데이트하여 연결 문자열을 보여줄 수 있습니까?

업데이트 : 좋습니다. 통합 Windows 인증을 사용하고 있습니다-> SQL Server에서 "xyz \ ASPNET"에 대한 SQL Server 로그인을 생성하거나 연결 문자열을 다음과 같이 변경해야합니다.

connectionString="Server=.\SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"

데이터베이스에 암호가 "top $ secret"인 사용자 "xyz"가있는 경우.


  • 다음 중 하나 : "xyz \ ASPNET"은 로그인이 아닙니다 (sys.server_principals에 있음).
  • 또는 : "xyz \ ASPNET"이 설정되었지만 데이터베이스 테스트 (sys.database_principals)의 사용자에 매핑되지 않았습니다.

두 번째 옵션을 선택하겠습니다. 오류 메시지는 기본 데이터베이스가 로그인으로 설정되지 않았거나 권한이 없다는 것을 의미합니다.

로그인으로 설정되었는지 테스트하려면

SELECT SUSER_ID('xyz\ASPNET') -- (**not** SUSER_SID)

NULL 인 경우

CREATE LOGIN [xyz\ASPNET] FROM WINDOWS

NULL이 아닌 경우

USE test
GO
SELECT USER_ID('xyz\ASPNET')

NULL 인 경우

USE test
GO
CREATE USER [xyz\ASPNET] FROM LOGIN [xyz\ASPNET]

로그인 문제에 대한 최상의 솔루션은 sqlServer에서 로그인 사용자를 만드는 것입니다. Windows 인증 (SQL Server Management Studio)을 사용하는 SQL Server 로그인을 만드는 단계는 다음과 같습니다.

  1. SQL Server Management Studio에서 개체 탐색기를 열고 새 로그인을 만들 서버 인스턴스의 폴더를 확장합니다.
  2. 보안 폴더를 마우스 오른쪽 단추로 클릭하고 새로 만들기를 가리킨 다음 로그인을 클릭합니다.
  3. 일반 페이지에서 로그인 이름 상자에 Windows 사용자 이름을 입력합니다.
  4. Windows 인증을 선택합니다.
  5. 확인을 클릭하십시오.

예를 들어 사용자 이름이 xyz\ASPNET이면이 이름을 로그인 이름 상자에 입력합니다.

또한 액세스하려는 데이터베이스에 대한 액세스를 허용하도록 사용자 매핑을 변경해야합니다.


나는이 문제가 있었고 그것을 해결 한 것은 다음과 같습니다.

  • IIS의 응용 프로그램 풀로 이동
  • 내 프로젝트 응용 프로그램 풀을 마우스 오른쪽 버튼으로 클릭하십시오.
  • 프로세스 모델 섹션에서 ID 열기
  • 사용자 지정 계정 옵션 선택
  • PC 사용자 이름과 암호를 입력하십시오.

대부분의 경우 로그인 문제가 아니라 데이터베이스 자체를 만드는 문제입니다. 따라서 데이터베이스를 생성하는 중에 오류가 발생하면 처음부터 생성되지 않습니다. 이 경우 사용자에 관계없이 로그인을 시도하면 로그인이 실패합니다. 이것은 일반적으로 db 컨텍스트의 논리적 오해로 인해 발생합니다.

브라우저에서 사이트를 방문하고 실제로 해당 오류 로그를 읽으면 코드 문제 (일반적으로 모델과 충돌하는 논리 문제)를 발견하는 데 도움이 될 수 있습니다.

내 경우에는 코드가 잘 컴파일되고 동일한 로그인 문제가 발생했습니다. 여전히 관리 스튜디오를 다운로드하는 동안 오류 로그를 살펴보고 db 컨텍스트 제약 조건을 수정하고 사이트가 정상적으로 실행되기 시작했습니다 .... 한편 관리 스튜디오는 여전히 다운로드 중입니다.


나를 위해 데이터베이스가 생성되지 않았고 EF 코드가 먼저 생성해야했지만 항상이 오류로 끝납니다. aspnet 코어 기본 웹 프로젝트에서 동일한 연결 문자열이 작동했습니다. 해결책은

_dbContext.Database.EnsureCreated()

첫 번째 데이터베이스 연결 전 (DB 시드 전).


문제

오류는 다음과 유사한 메시지로 나타납니다.

로그인에 의해 요청 된 "DATABASE NAME"데이터베이스를 열 수 없습니다. 로그인에 실패했습니다. 사용자 XYZ가 로그인하지 못했습니다.

  • 이 오류는 일반적으로 간단한 Visual Studio 또는 전체 컴퓨터 다시 시작으로 수정할 수 없습니다.
  • 오류는 잠긴 것처럼 보이는 데이터베이스 파일로도 발견 될 수 있습니다.

수정

솔루션은 다음 단계에 있습니다. 데이터베이스의 데이터를 잃지 않으며 데이터베이스 파일을 삭제해서는 안됩니다!

전제 조건 : SQL Server Management Studio (Full 또는 Express)를 설치해야합니다.

  1. SQL Server Management Studio 열기
  2. "서버에 연결"창 (파일-> 개체 탐색기 연결)에서 다음을 입력합니다.
    • 서버 유형 : 데이터베이스 엔진
    • 서버 이름 : (localdb) \ v11.0
    • 인증 : [로컬 db를 만들 때 사용한 모든 것. 아마도 Windows 인증).
  3. "연결"을 클릭하십시오.
  4. 개체 탐색기에서 "데이터베이스"폴더를 확장합니다 (보기-> 개체 탐색기, F8).
  5. 데이터베이스를 찾으십시오. 데이터베이스 (.mdf) 파일의 전체 경로로 이름을 지정해야합니다.
    • 데이터베이스 이름 끝에 "(Pending Recovery)"라는 메시지가 표시되거나 데이터베이스를 확장하려고 할 때 오류 메시지가 표시되거나 표시되지 않을 수 있습니다.
    • 이 문제! 데이터베이스가 본질적으로 충돌했습니다 ..
  6. 데이터베이스를 마우스 오른쪽 버튼으로 클릭 한 다음 "작업-> 분리 ..."를 선택합니다.
  7. In the detach window, select your database in the list and check the column that says "Drop Connections"
  8. Click OK.
  9. You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
  10. After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.

The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed


I tried to update the user, and it worked. See the command below.

USE ComparisonData// databaseName
EXEC  sp_change_users_login @Action='update_one', @UserNamePattern='ftool',@LoginName='ftool';

Just replace user('ftool') accordingly.


I used Windows authentication to connect to local database .mdf file and my local server was sql server 2014. My problem solved using this connection string:

string sqlString = " Data Source = (LocalDB)\\MSSQLLocalDB;" + "AttachDbFilename = F:\\.........\\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception. To resolve this issue follow below steps.

  1. Make sure the object explorer is pointed to a system database like master.
  2. Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
  1. Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO

The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.


I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.


This Works for me.

  1. Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
  2. In newly opened screen of Login Properties, go to the “User Mapping” tab.
  3. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
  4. Click OK.

Read this blog.

http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/


It also happen when you type wrong name of DB

ex : xxx-db-dev to xxx-dev-db

Sometime, it's just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first


Inspired by cyptus's answer I used

_dbContext.Database.CreateIfNotExists();

on EF6 before the first database contact (before DB seeding).


I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!

Edit: Setting the login as db owner solved the next problem, too


Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result - you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.

My apologies about bad english. Kind regards, Ignat.


In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:

2016-10-28 10:27:10.86 Logon       Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server      SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.

So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.


Even if you've set the login as DB owner and set the user mapping for the database that will use the login, check that the actual DB user (not just the login) has the role of 'owner'.


NB: If using a windows service to host the webservice.

You have to insure that your webservice is using the right Log on account to connect to SQL Server.

  • Open services(I assume the windows service has been install)
  • Right click on the service and goto properties.
  • Click on "Log On" Tab
  • Click on "This account" radio button
  • Click "Browse"
  • Enter Pc user name in Text Field and click "Check Name" Button to the right.
  • Click on text in Text Field, press "OK" button
  • enter login password and Apply

If you haven't created the database in your server you will get the same login error.Make sure that the database exist before you login.


In my case, I was running a Windows Service under "System" identity. The error was:

System.Data.SqlClient.SqlException (0x80131904): 
Cannot open database "MyDbName" requested by the login. The login failed.
Login failed for user 'MYDOMAINNAME\HOSTNAME$'.

The problem is that the error is very misleading. Even after I added 'MYDOMAINNAME\HOSTNAME$' login to the database, and granted this login sysadmin access and added a user for that login on my target database, and made that user dbowner, I was still getting the same error. Apparently I needed to do the same for 'NT AUTHORITY\SYSTEM' login. After I did that, I was able to login without a problem. I don't know why the error message complains about 'MYDOMAINNAME\HOSTNAME$'. I deleted that login and the corresponding user and everything still works.

참고URL : https://stackoverflow.com/questions/2575907/cannot-open-database-test-requested-by-the-login-the-login-failed-login-fail

반응형