使用 web.config 授权元素时未触发 OWIN 质询

Flo*_*eda 3 c# asp.net owin asp.net-identity identityserver3

我正在将 Web 表单应用程序从表单身份验证迁移到 OpenID Connect(使用 OWIN 和 IdentityServer3)。该应用程序在 web.config 中已经有很多“授权”元素(针对不同位置),我想在迁移到 OWIN 后重用这些元素。

<authorization>
   <deny users="?" />
</authorization>
<location path="Path/Page.aspx">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>
...
Run Code Online (Sandbox Code Playgroud)

问题是,在我切换到 OWIN 而不是被重定向到登录页面后,我得到了 401(未经授权)。

目前,将用户重定向到登录页面的唯一方法是在 Page_Load 事件中手动进行质询:

if (!Request.IsAuthenticated)
{
   HttpContext.Current.GetOwinContext().Authentication.Challenge();
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Startup.Auth 的样子:

public void ConfigureAuth(IAppBuilder app)
        {
            //reset the mapping dictionary to ensure the claims are not mapped to .NET standard claims
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",                    
                AuthenticationMode = AuthenticationMode.Active          
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "id",
                Authority = IdentityConstants.BaseAddress,
                RedirectUri = "uri",
                ResponseType = "code id_token token",                    
                SignInAsAuthenticationType = "ApplicationCookie",
                Scope = "openid profile email roles offline_access",
                ...
            }
...
Run Code Online (Sandbox Code Playgroud)

有没有办法利用 web 配置中现有的授权元素,这样我就不必在代码中再次进行这些检查?

小智 7

在 app.UseOpenIdConnectAuthentication 之后添加以下代码:

app.UseStageMarker(PipelineStage.Authenticate);
Run Code Online (Sandbox Code Playgroud)

这将指示 Owin 在集成管道中运行。