Azure活动目录|基于角色的授权

时间:2018-09-25 07:05:44

标签: c# azure azure-active-directory owin owin-middleware

我尝试了跨Internet的Azure Active Directory的各种身份验证方案。所有示例仅集中于通过身份验证进行授权。我一直在寻找AAD App Registration中基于角色的用户授权。

Auth() Scenarios

例如,

.. \ Controller \ ArtistController.cs:

public class ArtistController : ApiController
    {
        [Authorize(Roles = "Admin, InternalAdmin")]
        public void Post(ArtistModel model)
        {
            // Do admin stuff here...
        }
    }

.. \ App_Start \ Startup.Auth.cs [不起作用]

public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        SaveSigninToken = true,
                        ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
                        RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
                    }
                });
    }

.. \ App_Start \ Startup.Auth.cs [工作中]

public void ConfigureAuth(IAppBuilder app)
{
    app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = ConfigHelper.ClientId,
                Authority = ConfigHelper.Authority,
                RedirectUri = "<<Home_Url>>",
                PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,

                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    NameClaimType = "upn",
                    RoleClaimType = "roles",    // The claim in the Jwt token where App roles are provided.
                },

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                        return System.Threading.Tasks.Task.FromResult(0);
                    }
                }
            });
}

我知道OWIN可以连接任何middleware来处理传入的http请求。 Auth MiddlewaresOpenIdWindowsBearerToken,...

根据此示例,UseOpenIdConnectAuthentication()是唯一通过middleware上的角色授权Web资源的正确UseWindowsAzureActiveDirectoryBearerAuthentication()吗?

请提出建议。

1 个答案:

答案 0 :(得分:1)

是的,OpenID是唯一适用于此的中间件。此时,OpenID Connect别无选择。

我发现设置角色的最佳方法是在清单中添加这些角色,然后对逻辑进行硬编码以赋予不同用户不同的权限。

这是到目前为止我找到的最好的样本。您只需将连接字符串添加到Azure SQL即可正常工作。 https://github.com/Azure-Samples/active-directory-dotnet-webapp-roleclaims