首页 > 解决方案 > 继承授权属性时 Azure AD OpenId 身份验证不起作用

问题描述

我尝试为使用 C# 4.7.2 完整框架编写的天蓝色应用服务验证用户身份。

身份验证在 Azure AD 上成为真正的 OpenId。

在控制器上使用 [Authorize] 属性时效果很好。

当我尝试使用从 AuthorizeAttribute 继承的属性来装饰控制器时,身份验证不再基于 Azure Ad(在云中或通过 iisexpress/localhost)

我需要重写 OnAuthorize 方法,因为应用程序根据上下文显示不同的数据,并且该上下文必须与某些用户安全组匹配。

即:url /context1 和 /context2 播放相同的代码,但 dbs 请求将因“where context = @context”条件而有所不同。所有 url 都将以 /context1 或 /context2 为前缀。

这是相关的代码:

        public void ConfigureAuth(IAppBuilder app)
        {

            //https://azure.microsoft.com/fr-fr/resources/samples/active-directory-dotnet-webapp-groupclaims/
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            string authority = $"https://login.microsoftonline.com/{ConfigurationManager.AppSettings["ida:Tenant"]}";
            string client = ConfigurationManager.AppSettings["ida:ClientId"];
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = client,
                    Authority = authority,
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        RoleClaimType = "groups",
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                        //MessageReceived = OnMessageReceived,
                        //SecurityTokenValidated = OnSecurityTokenValidated,
                        //AuthenticationFailed = OnAuthenticationFailed,
                        AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                        //SecurityTokenReceived = OnSecurityTokenReceived
                    }
                });
        }

“OnRedirectToIdentityProvider”帮助我检查是否调用了 azure AD 身份验证。

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {

        public override void OnAuthorization(AuthorizationContext context)
        {
            //OnRedirectToIdentityProvider has not been called
            //Checking that the authenticated user is in the right
            //security group to grant access to /context1 or /context2
        }
}

我希望在 OnAuthorize 被覆盖后调用 Startup.cs 配置。

谢谢你的帮助。

标签: c#azureinheritanceazure-active-directoryonauthorization

解决方案


在等待响应并尝试简化授权时,我遇到了另一个问题,并在搜索时找到了答案。

若要继续对 Azure AD 进行身份验证,可以重写 AuthorizationCore 方法。

这是新代码:

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase context)
        {
            if (!base.AuthorizeCore(context))
                return false;
            //Custom actions
        }
    }

问候。


推荐阅读