插入授权属性时,Azure AD OpenId身份验证不起作用

时间:2019-04-17 09:49:59

标签: c# azure inheritance azure-active-directory onauthorization

我尝试使用C#4.7.2完整框架编写的Azure应用服务对用户进行身份验证。

在Azure AD上将身份验证设为真实的OpenId。

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

当我尝试使用AuthorizeAttribute属性中的内容修饰控制器时,身份验证不再基于Azure广告(在云中或通过iisexpress / localhost)

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

即:    urls / context1和/ context2播放相同的代码,但dbs请求将因“ where context = @context”条件而有所不同。所有网址都将以/ 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配置。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

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

这是新代码:

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

致谢。