我在面向 .net 5.0 的 IIS 上托管了 Blazor 服务器应用程序。 我在 IIS 上启用了 Windows 身份验证,当它在 IIS 下运行时,我总是得到应用程序池标识,而不是当前登录的用户。
这是我的 startup.cs 包含的内容:
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddScoped<AuthenticationStateProvider, WinAuthStateProvider>()
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
app.UseAuthentication();
app.UseAuthorization();
这是我对 WinAuthStateProvider 的实现
public class WinAuthStateProvider : AuthenticationStateProvider
{
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
//Getting logged in windows user name
#pragma warning disable CA1416 // Validate platform compatibility
var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
#pragma warning restore CA1416 // Validate platform compatibility
/*//Logic for fetching role from DB — Here you can get other details about user from DB also
string role = UserService.getRole(user.Split('\\')[1]);*/
//Generating new Authentication state with claims if user have any role from DB
if (!string.IsNullOrEmpty(user))
{
var windowsAuth = new ClaimsIdentity(new List<Claim>()
{
new Claim(ClaimTypes.Name, user.Split('\\')[1]),
//new Claim(ClaimTypes.Role, role)
}, "windows");
return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(windowsAuth)));
}
else
{
var anonymous = new ClaimsIdentity();
return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(anonymous)));
}
}
}
这是我的 app.razor
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
这是我想在我的组件上打印的内容:
<AuthorizeView>
<Authorized>
<a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
<a href="Identity/Account/LogOut">Log out</a>
</Authorized>
<NotAuthorized>
<a href="Identity/Account/Register">Register</a>
<a href="Identity/Account/Login">Log in</a>
</NotAuthorized>
</AuthorizeView>
当它在 IIS Express 下本地运行时,它会生成正确的用户名。当我部署到 IIS 时,它总是为我生成应用程序池用户。
我尝试禁用匿名身份验证并仅保持启用 Windows 身份验证无济于事。
有很多线程提出了不同的解决方案,我在过去几天尝试了几乎所有的解决方案,但仍然面临同样的问题。
有人可以帮我解决这个问题吗?
谢谢