【发布时间】:2022-11-29 13:57:12
【问题描述】:
我正在尝试在 Visual Studio 2022 中设置具有 Windows 身份验证的 MVC 核心 Web 应用程序,但我无法使其正常工作。
我创建一个新项目并选择 Windows 身份验证选项。我立即尝试运行该应用程序,但出现空白页面。
为了进行故障排除,我添加了以下 else 子句,以便我可以查看我的开发机器上的问题所在。
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
// Development Environment
app.UseStatusCodePages();
}
然后我可以看到我有一个“401 Unauthorised”状态代码。然后,如果我将 [AllowAnonymous] 添加到我的索引操作中,我终于可以看到主页,但未显示我的 Windows 用户名。我希望看到右上角显示“你好用户名”,但我似乎没有经过身份验证,更不用说授权了。
除了上面的两个故障排除步骤之外,这是一个开箱即用的全新项目,但我在下面粘贴了我的 Program.cs 以供参考。
我需要做什么才能使 Windows 身份验证正常工作?
谢谢
using Microsoft.AspNetCore.Authentication.Negotiate;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
// Development Environment
app.UseStatusCodePages();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
【问题讨论】:
标签: asp.net-core-mvc windows-authentication