![](/img/trans.png)
[英]CREATE DATABASE permission denied in database 'master'. EF Code-first asp.net Core 3.1
[英]How to implement ASP.NET identity: CREATE DATABASE permission denied in database 'master'
首先,我已經在這里查了一下: ASP.Net Identity如何設置目標DB?
我現在收到這個錯誤
數據庫“master”中的CREATE DATABASE權限被拒絕。
在這行代碼上:
Dim user As User = manager.Find(Trim(Username.Text), Trim(Password.Text))
完整錯誤:
[SqlException(0x80131904):數據庫'master'中的CREATE DATABASE權限被拒絕。
System.Data.SqlClient.SqlConnection.OnError(SqlException異常,Boolean breakConnection,Action1 wrapCloseInAction) +3249852
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +345
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4927
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1287
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 wrapCloseInAction) +3249852
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +345
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4927
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1287
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 wrapCloseInAction) +3249852
1 completion,String methodName,Boolean sendToPipe,Int32 timeout,Boolean asyncWrite)+367
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +345
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4927
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1287
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource
System.Data.SqlClient.SqlCommand.ExecuteNonQuery()+386
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func
3操作,TInterceptionContext interceptionContext,Action3 executing, Action
3執行)+965
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand命令,DbCommandInterceptionContext interceptionContext)+505
System.Data.Entity.SqlServer。<> c__DisplayClass1a.b__19(DbConnection conn)+136
System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection,Action1 act) +347
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +347
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +347
1 act)+916
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action
System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +117
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +117
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +117
1 commandTimeout,StoreItemCollection storeItemCollection)+212
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable
System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection連接)+172
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)+175
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)+116
System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext,Func3 createMigrator, ObjectContext objectContext) +121
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +169
System.Data.Entity.CreateDatabaseIfNotExists3 createMigrator, ObjectContext objectContext) +121
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +169
System.Data.Entity.CreateDatabaseIfNotExists3 createMigrator, ObjectContext objectContext) +121
1.InitializeDatabase(TContext context)+257
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +169
System.Data.Entity.CreateDatabaseIfNotExists
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)+72
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()+483
System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +177
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1.PerformAction(TInput input) +177
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1.PerformAction(TInput input) +177
1 action)+274
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)+37
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +76
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +76
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +76
1.get_InternalContext()+ 21
System.Data.Entity.Internal.Linq.InternalSet
System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +59
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1.System.Linq.IQueryable.get_Provider() +59
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1.System.Linq.IQueryable.get_Provider() +59
1 source,Expression
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 predicate, CancellationToken cancellationToken) +208
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 predicate, CancellationToken cancellationToken) +208
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 predicate, CancellationToken cancellationToken) +208
1 source,Expression`1謂詞)+172
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryableMicrosoft.AspNet.Identity.EntityFramework.d__6c.MoveNext()+502
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任務任務)+13855856
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任務任務)+61
Microsoft.AspNet.Identity.CultureAwaiter1.GetResult() +48
Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +357
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func1.GetResult() +48
Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +357
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func1.GetResult() +48
1 func)+348
Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +357
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func
C:\\ MyApp \\ Login_identity.aspx.vb中的MyApp.Login_identity.UserLogin_Click(Object sender,EventArgs e):168
System.Web.UI.WebControls.Button.OnClick(EventArgs e)+11747645
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)+150
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)+3360
我將AppModel.vb
的DbContext
初始化更改為現有的連接字符串conn1
,該字符串指向已轉換為新標識表的SQL Server數據庫。
我的連接字符串:
<add name="conn1"
connectionString="data source=(local)\sqlexpress;Initial Catalog=myapp;User Id=sa;Password=XXXX;"
providerName="System.Data.SqlClient" />
AppModel.vb
:
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports System.Data.Entity
Imports System.Linq
Imports System.Web
Namespace AspnetIdentitySample.Models
Public Class ApplicationUser
Inherits IdentityUser
' HomeTown will be stored in the same table as Users
Public Property HomeTown() As String
Get
Return m_HomeTown
End Get
Set(value As String)
m_HomeTown = Value
End Set
End Property
Private m_HomeTown As String
Public Overridable Property ToDoes() As ICollection(Of ToDo)
Get
Return m_ToDoes
End Get
Set(value As ICollection(Of ToDo))
m_ToDoes = Value
End Set
End Property
Private m_ToDoes As ICollection(Of ToDo)
' FirstName & LastName will be stored in a different table called MyUserInfo
Public Overridable Property MyUserInfo() As MyUserInfo
Get
Return m_MyUserInfo
End Get
Set(value As MyUserInfo)
m_MyUserInfo = Value
End Set
End Property
Private m_MyUserInfo As MyUserInfo
End Class
Public Class MyUserInfo
Public Property Id() As Integer
Get
Return m_Id
End Get
Set(value As Integer)
m_Id = Value
End Set
End Property
Private m_Id As Integer
Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(value As String)
m_FirstName = Value
End Set
End Property
Private m_FirstName As String
Public Property LastName() As String
Get
Return m_LastName
End Get
Set(value As String)
m_LastName = Value
End Set
End Property
Private m_LastName As String
End Class
Public Class ToDo
Public Property Id() As Integer
Get
Return m_Id
End Get
Set(value As Integer)
m_Id = Value
End Set
End Property
Private m_Id As Integer
Public Property Description() As String
Get
Return m_Description
End Get
Set(value As String)
m_Description = Value
End Set
End Property
Private m_Description As String
Public Property IsDone() As Boolean
Get
Return m_IsDone
End Get
Set(value As Boolean)
m_IsDone = Value
End Set
End Property
Private m_IsDone As Boolean
Public Overridable Property User() As ApplicationUser
Get
Return m_User
End Get
Set(value As ApplicationUser)
m_User = Value
End Set
End Property
Private m_User As ApplicationUser
End Class
Public Class MyDbContext
Inherits IdentityDbContext(Of ApplicationUser)
Public Sub New()
MyBase.New("conn1") 'DefaultConnection
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
MyBase.OnModelCreating(modelBuilder)
' Change the name of the table to be Users instead of AspNetUsers
modelBuilder.Entity(Of IdentityUser)().ToTable("Users")
modelBuilder.Entity(Of ApplicationUser)().ToTable("Users")
End Sub
Public Property ToDoes() As DbSet(Of ToDo)
Get
Return m_ToDoes
End Get
Set(value As DbSet(Of ToDo))
m_ToDoes = Value
End Set
End Property
Private m_ToDoes As DbSet(Of ToDo)
Public Property MyUserInfo() As DbSet(Of MyUserInfo)
Get
Return m_MyUserInfo
End Get
Set(value As DbSet(Of MyUserInfo))
m_MyUserInfo = Value
End Set
End Property
Private m_MyUserInfo As DbSet(Of MyUserInfo)
End Class
End Namespace
UPDATE
根據評論,我也在這里查看 。
我真的不明白為什么這是一個角色問題,因為我正在重用一個已經正常工作的連接字符串來更新其他(非身份相關的)表。 此外,我不明白為什么錯誤引用master
表,因為我預計我不會嘗試通過manager.Find
方法以任何方式連接到該表。
無論如何,我正在測試的用戶已經被分配到sysadmin
角色:
更新2
好的,感謝Jeremy在下面的評論我更近了一步......我需要將用戶IIS APPPOOL\\.NET v4.5
到角色sysadmin
,因為那是用戶連接,如SQL Server分析器中所示(盡管我是將此用戶添加到此角色時,不確定安全風險)。 無論如何,Find方法不再拋出錯誤並使用SQL Server探查器我看到執行此代碼時觸發了SQL語句Dim user As User = manager.FindByName(Trim(Username.Text))
exec sp_executesql N'SELECT TOP (1)
[Extent1].[Id] AS [Id],
[Extent1].[ApplicationId] AS [ApplicationId],
[Extent1].[MobileAlias] AS [MobileAlias],
[Extent1].[IsAnonymous] AS [IsAnonymous],
[Extent1].[LastActivityDate] AS [LastActivityDate],
[Extent1].[MobilePIN] AS [MobilePIN],
[Extent1].[LoweredEmail] AS [LoweredEmail],
[Extent1].[LoweredUserName] AS [LoweredUserName],
[Extent1].[PasswordQuestion] AS [PasswordQuestion],
[Extent1].[PasswordAnswer] AS [PasswordAnswer],
[Extent1].[IsApproved] AS [IsApproved],
[Extent1].[IsLockedOut] AS [IsLockedOut],
[Extent1].[CreateDate] AS [CreateDate],
[Extent1].[LastLoginDate] AS [LastLoginDate],
[Extent1].[LastPasswordChangedDate] AS [LastPasswordChangedDate],
[Extent1].[LastLockoutDate] AS [LastLockoutDate],
[Extent1].[FailedPasswordAttemptCount] AS [FailedPasswordAttemptCount],
[Extent1].[FailedPasswordAttemptWindowStart] AS [FailedPasswordAttemptWindowStart],
[Extent1].[FailedPasswordAnswerAttemptCount] AS [FailedPasswordAnswerAttemptCount],
[Extent1].[FailedPasswordAnswerAttemptWindowStart] AS [FailedPasswordAnswerAttemptWindowStart],
[Extent1].[Comment] AS [Comment],
[Extent1].[Email] AS [Email],
[Extent1].[EmailConfirmed] AS [EmailConfirmed],
[Extent1].[PasswordHash] AS [PasswordHash],
[Extent1].[SecurityStamp] AS [SecurityStamp],
[Extent1].[PhoneNumber] AS [PhoneNumber],
[Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Extent1].[LockoutEnabled] AS [LockoutEnabled],
[Extent1].[AccessFailedCount] AS [AccessFailedCount],
[Extent1].[UserName] AS [UserName]
FROM [dbo].[AspNetUsers] AS [Extent1]
WHERE ((UPPER([Extent1].[UserName])) = (UPPER(@p__linq__0))) OR ((UPPER([Extent1].[UserName]) IS NULL) AND (UPPER(@p__linq__0) IS NULL))',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'flo@outlook.com'
奇怪的是:當我直接在SQL Server Management Studio中執行它時,我得到一條返回的記錄,但在我的代碼中,變量user
是Nothing
....它可以是什么?
您的連接字符串包含“User Id = sa; Password = XXXX”,因此該連接嘗試使用SQL Server身份驗證。 您的SSMS登錄屬性的標題欄似乎在標識Windows帳戶,這意味着有人認為應該使用Windows身份驗證。 然而,該連接正在嘗試使用SQL Server身份驗證(而不是Windows身份驗證)。 如果尚未配置,則可以更改SQL Server的身份驗證模式以支持SQL身份驗證和Windows身份驗證(“混合模式”身份驗證),請參閱https://msdn.microsoft.com/en-us/library/ms188670.aspx 。
或者,可以將連接字符串更改為使用Windows身份驗證/集成安全性,按照https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#integratedsecurity
如果您的應用程序池在NETWORK SERVICE標識下運行,請嘗試此操作。 然后為“NT AUTHORITY \\ NETWORK SERVICE”授予SysAdmin角色:
或者將SysAdmin提供給運行應用程序池的帳戶。
如果這不起作用,請檢查以下任何解決方案是否有幫助: 在數據庫'master'中創建數據庫權限被拒絕(EF代碼優先)
編輯:
給所有這些帳戶sysAdmin不是很安全。 在您開始工作之后,將SQL安全性加強到dbReader和dbWriter角色。
FindByName方法出了什么問題?
現在沒有異常,問題是沒有數據返回我認為仍然存在權限。
由於您在連接字符串中使用SQL身份驗證,您可以嘗試使用Windows集成嗎? 否則,請嘗試在連接字符串中使用appPool IIS帳戶憑據,看看是否會產生錯誤的線索?
為什么要使用身份字段而不是在NVARCHAR()字段中使用HASH值?
例如:您可以從用戶(或其字段的連接)獲取單個數據,從.NET Cryptography庫計算HASH並使用數據設置NVARCHAR()。
通過這種方式(假設您正在使用SHA-512 HASH),您將能夠擁有一個單獨數據的Base64字符串,就像身份本身一樣。
但是,如果您的目標與動量有一致 ,您可以獲取用戶數據,加上當前日期時間,計算其HASH並將此數據保存為記錄的標識。
您的用戶應添加到dbcreator角色。
否則,您不能創建新數據庫。
系統管理員/公眾是不夠的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.