gpt4 book ai didi

ASP.NET OWIN WebForms 需要授权所有页面

转载 作者:行者123 更新时间:2023-12-04 05:23:56 25 4
gpt4 key购买 nike

我使用 Visual Studio 2013 Update 2 创建了一个新的 ASP.NET WebForms 应用程序。然后我更新了所有 NuGet 包并删除了所有 OAuth 内容,因为我只需要我熟悉的“表单”身份验证。

我想要的是配置 OWIN/ASP.NET 身份框架 这样所有页面都需要授权 ,包括默认页面 - 所以用户应该看到的第一页是登录页面。这样做的正确方法是什么?我在 Internet 上找不到任何资源来展示如何使用 OWIN/ASP.NET 标识保护 WebForms 页面。

我将以下 XML 添加到主 web.config 文件的底部,但出现错误:

<authorization>
<deny users="?"/>
</authorization>

错误是: 无法访问请求的页面,因为该页面的相关配置数据无效。

最佳答案

您是对的,没有关于将经典 ASP.Net 授权与 OWIN 安全中间件一起使用的资源。
我正在使用 ASP.Net 网页,所以我的实验与您的相似(我们都尝试保护 aspx 或 cshtml 的静态文件)。
我的实验太可怕了。我正要用头撞墙。
最后我发现了如何让它运行。这就是我所做的:

  • Web.config:保护除匿名用户必须可用的特殊页面之外的所有内容。

  • <configuration>
    <system.web>
    <authorization>
    <deny users="?" />
    </authorization>
    </system.web>

    <location path="shell.cshtml">
    <system.web>
    <authorization>
    <allow users="*" />
    </authorization>
    </system.web>
    </location>

    <location path="notFound.cshtml">
    <system.web>
    <authorization>
    <allow users="*" />
    </authorization>
    </system.web>
    </location>

    <location path="security/login.cshtml">
    <system.web>
    <authorization>
    <allow users="*" />
    </authorization>
    </system.web>
    </location>
    </configuration>
  • OWIN启动类:

  •     public static class Startup
    {
    public static void Configuration(IAppBuilder app)
    {
    var cookieExpiration = TimeSpan.FromMinutes(20);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
    AuthenticationMode = AuthenticationMode.Active,
    CookieName = "efa",
    ExpireTimeSpan = cookieExpiration,
    SlidingExpiration = true,
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    Provider = new CookieAuthenticationProvider
    {
    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, User, long>(
    validateInterval: cookieExpiration,
    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
    getUserIdCallback: identity => Identity.Identity.ExtractIdFromClaims(identity))
    }
    });

    app.UseWebApi(new HttpConfig());
    }
    }
    设置 AuthenticationMode = AuthenticationMode.Active 至关重要.我花了一整天的时间来发现这一点。如果将其设置为 Passive ,身份验证中间件不会填充 HTTP 上下文的 Identity 和 Principal 对象,并且授权模块将禁止所有请求。
    这将使经典 UrlAuthorization模块根据 OWIN 中间件填充的身份为您工作。需要注意的是,Nuget 包 Microsoft.Owin.Host.SystemWeb必须安装,否则 OWIN 不会与 ASP.Net 管道集成。
    您也可以使用这些现代 OWIN 授权模块
    http://leastprivilege.com/2014/06/24/resourceaction-based-authorization-for-owin-and-mvc-and-web-api/
    它们是高度可定制的,可以保护 MVC Controller 、Web API Controller 和静态文件。

    关于ASP.NET OWIN WebForms 需要授权所有页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24614801/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com