我尝试为使用 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 配置。
谢谢你的帮助。