【问题标题】:ASP.NET MVC - Allow internal anonymous users, require windows authentication on externalASP.NET MVC - 允许内部匿名用户,需要在外部进行 Windows 身份验证
【发布时间】:2012-10-09 15:10:47
【问题描述】:

是否可以根据请求的区域设置授权?基本上它是一个内网类型的应用程序,只有很少的敏感信息。

如果请求是从组织内部执行的,则允许匿名用户是可以的。

但是,如果是外部请求,他们应该会收到 401 授权挑战。 外部请求来自单个防火墙,因此 IP/IP 范围应该可以指定它是外部请求还是内部请求。

目前在 web.config 文件中为 Windows 身份验证配置。

<authentication mode="Windows" />
<authorization>
  <deny users="?" />
</authorization>

【问题讨论】:

    标签: asp.net-mvc authentication


    【解决方案1】:

    直接在防火墙上处理此规则会更容易。

    作为替代方案,您可以在 IIS 级别配置 IP Security 并按客户端 IP 进行过滤。

    但如果你无法控制防火墙,你可以编写一个自定义的 Authorize 属性来检查传入的 IP 地址并允许/拒绝请求:

    public class IpBasedAuthorizeAttribute: AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var ip = httpContext.Request.UserHostAddress;
            return IsAllowed(ip);
        }
    
        private bool IsAllowed(string ip)
        {
            // TODO: do your checks here and return true or false
            // depending on whether the IP address is allowed to 
            // access the application or not
            throw new NotImplementedException();
        }
    }
    

    然后您可以使用此属性装饰单个控制器/操作,或者如果您希望它应用于所有请求,则将其注册为全局授权属性:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new IpBasedAuthorizeAttribute());
    }
    

    【讨论】:

    • 完美!这正是我想要的。谢谢!
    猜你喜欢
    • 2023-04-09
    • 2018-04-30
    • 1970-01-01
    • 2013-05-17
    • 2012-08-29
    • 2011-04-16
    • 2017-08-16
    • 2016-11-01
    • 1970-01-01
    相关资源
    最近更新 更多