我在login.microsoftonline.com和我的应用程序之间遇到了无限重定向循环。 我的项目正在在Asp.net 4.8 Web Forms项目中实现身份验证和授权。 我能够使用默认的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);
}
}
Web.Config
<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
。我已通过更新web config来完成此操作:
<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 错误?