首页 > 解决方案 > ASP.NET Core 3.1 Web API - 为不使用它的控制器禁用 Windows 身份验证

问题描述

我正在开发一个部署在 IIS 上的 ASP.NET Core Web 应用程序,它有两个控制器。一个控制器下的动作方法被内网应用程序使用,因此控制器使用windows身份验证,而另一个控制器下的动作方法可以从内网外部使用,因此控制器使用不记名令牌授权。

两个控制器的身份验证工作正常,直到某一点。如果一个操作方法的不记名令牌身份验证失败(例如,如果不记名令牌过期),那么我会从浏览器弹出一个请求凭据,因为 IIS 正在发回WWW-Authenticate: NegotiateWWW-Authenticate: NTLM在响应标头中。我认为这是因为在 IIS 中为整个 Web 应用程序启用了 Windows 身份验证。(我可能应该指定我在 IIS 中也启用了匿名身份验证)。

当不使用 Windows 身份验证的操作方法的承载令牌身份验证失败时,是否有办法阻止 IIS 在响应标头中发送WWW-Authenticate: NegotiateWWW-Authenticate: NTLM ?

我可以使用像下面这样的 Startup 类很容易地复制它:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthentication().AddJwtBearer();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

和如下所示的控制器:

 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [Route("[controller]")]
    [ApiController]
    public class BearerController : ControllerBase
    {
        // GET: /Bearer
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

到目前为止,我尝试的是从传递给方法的回调中设置DefaultChallengScheme, DefaultForbidScheme, DefaultSignInSchemeto ,但没有成功。JwtBearerDefaults.AuthenticationSchemeservices.AddAuthentication

我还研究了通过更改我的 Web 应用程序来禁用不使用它的控制器的 Windows 身份验证,web.config但我没有找到一种方法来仅针对 URL 路径禁用它,而仅针对整个 Web 应用程序禁用它。

标签: c#asp.net-coreauthenticationiisasp.net-core-3.1

解决方案


推荐阅读