c# - 继承授权属性时 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 配置。
谢谢你的帮助。
解决方案
在等待响应并尝试简化授权时,我遇到了另一个问题,并在搜索时找到了答案。
若要继续对 Azure AD 进行身份验证,可以重写 AuthorizationCore 方法。
这是新代码:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase context)
{
if (!base.AuthorizeCore(context))
return false;
//Custom actions
}
}
问候。
推荐阅读
- reactjs - 在 setState 中使用 async-await
- flutter - '_route == ModalRoute.of(context)': 不正确
- python - 返回最常见的元素作为字符串而不是列表 python
- android - Android Studio Navigation:从上方菜单栏捕获导航返回事件
- python - 解析来自 JSON URL 的信息后,如何在 if-else 语句中不打印多次就结束 for 循环
- git - 如何使用 Jenkins 管道将代码合并回 Github
- reactjs - react-i18next / i18n 遵循什么语言代码的 ISO 标准?
- flutter - 将 GridView 添加到列表视图的末尾
- tensorflow - Keras 在 LSTM 中降低维度,不知道为什么
- python - 从 tensorflow 中保存在 csv 文件中的最大 epoch 恢复训练