我有一个Asp.net MVC应用程序,在其中使用Azure AD身份验证来对用户进行身份验证。我想允许用户无需登录即可访问某些api控制器。我尝试将[AllowAnonymous]属性放在控制器上以跳过身份验证的这些控制器,但是它始终重定向到Microsoft登录页面以获取凭据。 Startup.cs中的代码片段:

public void ConfigureAuth(IAppBuilder app)
    {
        string clientId = GetConfigValue("ida_ClientId");
        string aadInstance = GetConfigValue("ida_AADInstance");
        string tenant = GetConfigValue("ida_Tenant");
        string domain = GetConfigValue("ida_Domain");
        string authority = GetConfigValue("ida_Authority");
        string postLogoutRedirectUri = GetConfigValue("ida_RedirectUri");

        bool devEnvironment = Convert.ToBoolean(GetConfigValue("DevEnvironment"));

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            CookieHttpOnly = true,
            CookieSecure = devEnvironment ? CookieSecureOption.SameAsRequest : CookieSecureOption.Always,
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            RedirectUri = postLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                }
            }
        });
    }

    private string GetConfigValue(string key)
    {
        if (RoleEnvironment.IsAvailable)
        {
            return RoleEnvironment.GetConfigurationSettingValue(key);
        }
        else
        {
            return ConfigurationManager.AppSettings[key];
        }
    }
}


如果我有任何遗漏,请告诉我。提前致谢

最佳答案

这是预期的行为。 Easy Auth被实现为本机IIS模块,与您的应用程序在同一沙箱中运行。启用后,分派给IIS工作进程的每个HTTP请求必须首先通过此模块,然后您的应用程序代码才有机会做出反应。

该请求将被分派到Web应用程序,除非经过身份验证,并且AllowAnonymous在这种情况下将不起作用。如果要允许匿名请求,则可以使用OWIN组件而不是使用Easy Auth来实现身份验证。

这是使用OpenId组件保护MVC的示例:

active-directory-dotnet-webapp-openidconnect

有关Easy Auth的更多详细信息,您可以参考CGillum的博客

Architecture of Azure App Service Authentication / Authorization

09-20 03:41