【发布时间】:2022-12-17 00:33:39
【问题描述】:
我在 login.microsoftonline.com 和我的应用程序之间遇到无限重定向循环。我的项目是在 Asp.net 4.8 Web 窗体项目中实现身份验证和授权。我可以使用默认的 Owin 启动文件添加身份验证,然后在 Web 配置文件中要求身份验证。以下要求用户在能够访问pages/AuthRequired之前必须先登录才能正常工作
StartupAuth.CS
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
private static string authority = ConfigurationManager.AppSettings["ida:Authority"];
private static string clientSecret = ConfigurationManager.AppSettings["AppRegistrationSecret-Local"];
public void ConfigureAuth(IAppBuilder app)
{
//for debugging
//IdentityModelEventSource.ShowPII = true;
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
ClientSecret = clientSecret,
RedirectUri = postLogoutRedirectUri,
//This allows multitenant
//https://github.com/Azure-Samples/guidance-identity-management-for-multitenant-apps/blob/master/docs/03-authentication.md
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = (context) =>
{
return Task.FromResult(0);
}
}
}
);
// This makes any middleware defined above this line run before the Authorization rule is applied in web.config
app.UseStageMarker(PipelineStage.Authenticate);
}
}
网页配置
<configuration>
...
<system.web>
<authentication mode="None" />
</system.web>
<location path="Pages/AuthRequired">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
...
</configuration>
我需要添加授权,这样只有具有管理员角色的用户才能访问Pages/AuthRequired。我通过更新网络配置来做到这一点:
<configuration>
...
<system.web>
<authentication mode="None" />
</system.web>
<location path="Pages/AuthRequired">
<system.web>
<authorization>
<allow roles="Admin" />
<deny users="*" />
</authorization>
</system.web>
</location>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
...
</configuration>
如果用户具有该角色,则向经过身份验证的页面添加授权可以正常工作,但如果没有该角色的用户尝试访问该页面,他们将被重定向回 login.microsoftonline.com,然后无限期地返回到应用程序环形。
我可以看到 Owin UseOpenIdConnectAuthentication 在未经授权时返回 302 响应,这导致了循环。
我该如何更改它,而不是将未经授权(但经过身份验证)的用户重定向到 login.microsoftonline.com,而是应将该用户定向到显示 401 错误的应用程序页面?
【问题讨论】:
标签: c# asp.net azure-active-directory owin