Sql server 在IIS上的Blazor Server应用程序中使用模拟对SQL Server进行身份验证
我有一个使用Windows身份验证在IIS上托管的intranet应用程序。现在,我需要根据SQL Server(在同一台服务器上运行)对用户进行身份验证。这是我使用的代码。GetDbUser触发一个简单的Sql server 在IIS上的Blazor Server应用程序中使用模拟对SQL Server进行身份验证,sql-server,iis,windows-authentication,blazor-server-side,impersonation,Sql Server,Iis,Windows Authentication,Blazor Server Side,Impersonation,我有一个使用Windows身份验证在IIS上托管的intranet应用程序。现在,我需要根据SQL Server(在同一台服务器上运行)对用户进行身份验证。这是我使用的代码。GetDbUser触发一个简单的queryString=“SELECT suser_sname()”到SQL Server。我得到一个错误: 用户NT权限\匿名登录登录失败 因此,模拟似乎无法正常工作。如果我注释掉RunImpersonated代码并在本地运行,它可以正常工作 private async Task DbCon
queryString=“SELECT suser_sname()”代码>到SQL Server。我得到一个错误:
用户NT权限\匿名登录登录失败
因此,模拟似乎无法正常工作。如果我注释掉RunImpersonated代码并在本地运行,它可以正常工作
private async Task DbConnectionTest()
{
var authState = await authenticationStateTask;
user = authState.User;
_dataBaseUser = "";
var Currentuser = (WindowsIdentity)user.Identity;
WindowsIdentity.RunImpersonated(Currentuser.AccessToken, () =>
{
string dbUser = GetDbUser();
_dataBaseUser = $"Database User-> {dbUser}";
});
}
这是数据库的代码
private string GetDbUser()
{
string queryString = "SELECT suser_sname()";
DataTable _table = new DataTable();
string myConnectionString = "Server = MyMSSQLServer; Database = testDB; Trusted_Connection = True;";
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
_table.Load(reader);
reader.Close();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
return _table.Rows[0].ItemArray[0].ToString();
}
使用AuthenticationStateProvider获取访问令牌
@inject AuthenticationStateProvider AuthenticationStateProvider
var token = ((WindowsIdentity)AuthenticationStateProvider.GetAuthenticationStateAsync().Result.User.Identity).AccessToken;
而不是
var Currentuser = (WindowsIdentity)user.Identity;
var token = Currentuser.AccessToken
使用AuthenticationStateProvider获取访问令牌
@inject AuthenticationStateProvider AuthenticationStateProvider
var token = ((WindowsIdentity)AuthenticationStateProvider.GetAuthenticationStateAsync().Result.User.Identity).AccessToken;
而不是
var Currentuser = (WindowsIdentity)user.Identity;
var token = Currentuser.AccessToken
您是否遵循了的配置说明?听起来你没有禁用匿名身份验证。我禁用了匿名身份验证winauth可以正常工作,但模拟部分不行。如果你不注释掉RunImpersonated代码并在本地运行,它能正常工作吗?Asp.net core不实现模拟,如果应用程序应代表用户执行操作,RunImpersonated可以执行。当您注释掉RunImpersonated代码时,它将使用应用程序的标识运行,而不是当前用户。确定。我刚刚指出,到目前为止,我的IIS设置对于windows身份验证是正确的。但我的模拟代码显然不是。同一域和应用程序池中的IIS和数据库是否具有登录标识?另一件事是您可以更改windows的提供程序、协商、NTML,然后重试。您是否遵循了的配置说明?听起来你没有禁用匿名身份验证。我禁用了匿名身份验证winauth可以正常工作,但模拟部分不行。如果你不注释掉RunImpersonated代码并在本地运行,它能正常工作吗?Asp.net core不实现模拟,如果应用程序应代表用户执行操作,RunImpersonated可以执行。当您注释掉RunImpersonated代码时,它将使用应用程序的标识运行,而不是当前用户。确定。我刚刚指出,到目前为止,我的IIS设置对于windows身份验证是正确的。但我的模拟代码显然不是。同一域和应用程序池中的IIS和数据库是否具有登录标识?另一件事是您可以更改windows的提供程序、协商、NTML,然后重试。