ASP.NET Core 应用程序,带 Windows 身份验证、Chrome,如何提示用户输入密码而不是获取 403?

问题描述 投票:0回答:1

我有一个使用 Windows 身份验证的 ASP.NET Core 8 Web 应用程序。并非组织中的所有用户都有权访问该应用程序。他们必须具有某些应用程序角色,并且这些角色在数据库中定义。

我使用声明转换器根据此代码从数据库中获取用户的角色以拉取,并将数据库中的角色添加为声明类型。

如果用户没有访问该应用程序的权限,则他/她没有任何角色。授权通过

Authorize(Roles = "...")
处理。

到目前为止一切顺利。

现在是我的问题。当我进行开发时(我使用IIS Express),我自己的Windows帐户没有访问该应用程序的权限,我必须使用特殊的测试帐户登录。问题是 Chrome 会自动对我进行身份验证,当我进入登陆页面时,应用程序会返回 403。

我找到了一个解决方法,那就是我在 Chrome 隐身窗口中打开应用程序,它总是提示我输入密码。

但是,我很好奇是否有办法在正常的 Chrome 窗口中提示输入密码。有趣的是,这个应用程序是从 .NET 框架到 .NET Core 的转换,每当我删除 cookie 时,Chrome 都会提示我在旧应用程序中输入密码。但在新版本中似乎没有可以删除的cookie。每次我访问任何内容时都会调用声明转换器。

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews()
  .AddRazorRuntimeCompilation();
  
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
  .AddNegotiate();

// builder.Services.AddAuthentication(IISServerDefaults.AuthenticationScheme);

builder.Services.AddTransient<IClaimsTransformation, AppClaimsTransformer>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(20);
    options.Cookie.Name = ".myapp.s";
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = //options.DefaultPolicy;    
        new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireRole(RolesConstants.AppUserRole)
                .Build();
});

builder.Services.Configure<IISServerOptions>(
    options =>
    {
        options.AutomaticAuthentication = true;
    });

// No need to add this
// builder.Services.AddRazorPages();

var app = builder.Build();

// For MVC error handling
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), appBuilder =>
{
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else 
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
});

// WebApiError handling
app.UseWhen(context =>
{
    var result = context.Request.Path.StartsWithSegments("/api");
    // log.Info($"{context.Request.Path}, {result}");
    return result;
}, appBuilder =>
{
    appBuilder.ConfigureExceptionHandler(log);
});

app.UseHttpsRedirection();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

谢谢

asp.net-core windows-authentication asp.net-core-8
1个回答
0
投票

如果禁用“AutomaticAuthentication”选项,您应该会得到您期望的行为。

© www.soinside.com 2019 - 2024. All rights reserved.