【问题标题】:Windows and Anonymous Authentication in .Net Core 2.0.Net Core 2.0 中的 Windows 和匿名身份验证
【发布时间】:2017-09-06 21:49:45
【问题描述】:

我正在尝试在 .Net Core 2.0 空 Web 应用程序中混合使用 Windows匿名 身份验证。我想避免使用 [Authorize] 属性,因为我不想使用 Mvc 或控制器。

我的设置如下:

  1. 我创建了一个空的 .Net Core 2.0 Web 应用程序

  2. 我转到项目属性 -> 调试 -> 选中“启用 Windows 身份验证”并禁用“启用匿名身份验证”。 现在 "windowsAuthentication": true 和 "anonymousAuthentication": false 出现在我的 "IIS" 下的 launchSettings.json 中。

  3. 在 Startup.cs 中,我在 ConfigureServices 中添加 services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme);https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#windows-authentication-httpsys--iisintegration 中所述

  4. 我添加了一个简单的Console.WriteLine(context.User.Identity.Name); 以查看它在 app.Run 中的工作并... 一切正常!

但是...一旦我在 launchSettings.json 中将“anonymousAuthentication”设置为 true,它就会停止工作,我无法弄清楚我可以做些什么来使 Windows 身份验证与它一起工作。 Context.User.Identity.IsAuthenticated 总是错误的。 如您所见,我的配置非常简单,我需要它保持这种状态。我想在某些动态路由上启用/禁用 Windows 身份验证,因此不能选择使用具有 [Authorize] 属性的控制器。

我想要实现的是一个简单的应用程序,其中 url “/authenticated” 会回复 context.User.Identity.Name 的值,而 url “/public” 会回复类似“这是一个公共页面! ”。 类似于 NTLM authentication on specific route in ASP.NET Core 但没有 [Authorize] 属性和控制器的东西。 资源非常稀缺......有人知道我可能会错过什么吗? 谢谢!

【问题讨论】:

    标签: c# asp.net .net authentication asp.net-core


    【解决方案1】:

    匿名优先。当您收到对应用程序受限部分的匿名请求时,您需要调用 httpContext.ChallengeAsync()。这将导致客户端在下一个请求时发送凭据。 Here's a test that does this.

    【讨论】:

    • 非常感谢! context.ChallengeAsync("Windows") 成功了!我发誓我试过 await context.ChallengeAsync(),但我使用“NTLM”作为架构参数,它告诉我身份验证架构不存在......不知道要传递什么值......
    【解决方案2】:

    在这个话题上浪费了一些时间之后,Tratcher 的回答救了我。对于一个非常简单的场景(匿名控制器 + windows 身份验证在其余部分受到限制),这里是一个快速入门(中间件):

    public class NtlmAndAnonymousSetupMiddleware
    {
        private readonly RequestDelegate next;
    
        public NtlmAndAnonymousSetupMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            if (context.User.Identity.IsAuthenticated || context.Request.Path.ToString().StartsWith("/Anonymous"))
            {
                await next(context);
                return;
            }
    
            await context.ChallengeAsync("Windows");
        }
    
    }
    

    我刚刚在Startup.Configure方法的开头插入了这个:

    app.UseMiddleware<NtlmAndAnonymousSetupMiddleware>();
    

    【讨论】:

    • 对我来说,这会生成“未注册身份验证处理程序。您是否忘记调用 AddAuthentication().Add[SomeAuthHandler]("Windows",...)?”但我确实在 Startup.cs 中定义了 AddAuthentication
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 2020-12-21
    • 2019-11-28
    • 2017-11-30
    • 2011-05-14
    • 2017-11-28
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多