c# - asp.net mvc 上的自定义授权属性

标签 c# asp.net asp.net-mvc azure adal

我有一个使用 Azure AAD 授权的 asp.net mvc 应用程序。该应用程序基于此 github 示例:

https://github.com/dushyantgill/VipSwapper/tree/master/TrainingPoint

此应用程序有一个自定义授权属性

  public class AuthorizeUserAttribute : AuthorizeAttribute
  {
        protected override void HandleUnauthorizedRequest(AuthorizationContext ctx)
        {
            if (!ctx.HttpContext.User.Identity.IsAuthenticated)
                base.HandleUnauthorizedRequest(ctx);
            else
            {
                ctx.Result = new ViewResult { ViewName = "Error", ViewBag = { message = "Unauthorized." } };
                ctx.HttpContext.Response.StatusCode = 403;
            }
        }
    }

但是这对我来说似乎很奇怪。

我在 Controller 上有这样的东西:

 public class GlobalAdminController : Controller
    {
        // GET: GlobalAdmin
        [AuthorizeUser(Roles = "admin")]
        public ActionResult Index()
        {
            return View();
        }
    }

正如您所看到的,此处使用了自定义属性,但请更深入地查看自定义属性的代码。 显然,在 if 和 ELSE 上,请求都未经过身份验证。

现在看一下这个屏幕截图。

没有意义吧? http://screencast.com/t/obqXHZJj0iNG

问题是我应该怎么做才能允许用户执行 Controller ?

更新1: 在我的身份验证流程中,我有以下内容

  public void ConfigureAuth(IAppBuilder app)
        {
            // configure the authentication type & settings
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            // configure the OWIN OpenId Connect options
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = SettingsHelper.ClientId,
                Authority = SettingsHelper.AzureADAuthority,
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // when an auth code is received...
                    AuthorizationCodeReceived = (context) => {
                        // get the OpenID Connect code passed from Azure AD on successful auth
                        string code = context.Code;

                        // create the app credentials & get reference to the user
                        ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
                        string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;

                        // use the ADAL to obtain access token & refresh token...
                        //  save those in a persistent store...
                        EfAdalTokenCache sampleCache = new EfAdalTokenCache(userObjectId);
                        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, sampleCache);

                        // obtain access token for the AzureAD graph
                        Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);

                        if (GraphUtil.IsUserAADAdmin(context.AuthenticationTicket.Identity))
                            context.AuthenticationTicket.Identity.AddClaim(new Claim("roles", "admin"));

                        // successful auth
                        return Task.FromResult(0);
                    },
                    AuthenticationFailed = (context) => {
                        context.HandleResponse();
                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false
                }
            });
        }

特别检查 IsAADAdmin 方法调用

/// <summary>
        /// The global administrators and user account administrators of the directory are automatically assgined the admin role in the application.
        /// This method determines whether the user is a member of the global administrator or user account administrator directory role.
        /// RoleTemplateId of Global Administrator role = 62e90394-69f5-4237-9190-012177145e10
        /// RoleTemplateId of User Account Administrator role = fe930be7-5e62-47db-91af-98c3a49a38b1
        /// </summary>
        /// <param name="objectId">The objectId of user or group that currently has access.</param>
        /// <returns>String containing the display string for the user or group.</returns>
        public static bool IsUserAADAdmin(ClaimsIdentity Identity)
        {
            string tenantId = Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string signedInUserID = Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
            string userObjectID = Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EfAdalTokenCache(signedInUserID));

            AuthenticationResult result = authContext.AcquireTokenSilent(
                SettingsHelper.AzureAdGraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            HttpClient client = new HttpClient();

            string doQueryUrl = string.Format("{0}/{1}/users/{2}/memberOf?api-version={3}",
                SettingsHelper.AzureAdGraphResourceId, tenantId,
                userObjectID, SettingsHelper.GraphAPIVersion);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, doQueryUrl);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = client.SendAsync(request).Result;

            if (response.IsSuccessStatusCode)
            {
                var responseContent = response.Content;
                string responseString = responseContent.ReadAsStringAsync().Result;
                var memberOfObjects = (System.Web.Helpers.Json.Decode(responseString)).value;

                if (memberOfObjects != null)
                    foreach (var memberOfObject in memberOfObjects)
                        if (memberOfObject.objectType == "Role" && (
                            memberOfObject.roleTemplateId.Equals("62e90394-69f5-4237-9190-012177145e10", StringComparison.InvariantCultureIgnoreCase) ||
                            memberOfObject.roleTemplateId.Equals("fe930be7-5e62-47db-91af-98c3a49a38b1", StringComparison.InvariantCultureIgnoreCase)))
                            return true;
            }

            return false;
        }

我 100% 确定用户处于管理员角色,因为当我调试时它返回 true 并且创建了声明

更新 2: 在调试时,我检查了 User.Claims 并且角色 admin 就在那里。 所以我不确定每个角色的授权如何与 User.IsInRole 一起使用

http://screencast.com/t/zUbwbpzn55qb

最佳答案

Esteban,您似乎错过了在ConfigureAuth 实现中设置角色声明类型。请参阅示例的第 55 行:https://github.com/dushyantgill/VipSwapper/blob/master/TrainingPoint/App_Start/Startup.Auth.cs#L55 。执行此操作后,User.IsInRole() 和 Authorize 属性将正常工作。

Regd 自定义授权属性的实现 - ASP.net 有一个错误,它会因授权失败返回 401 错误(而不是 403)(这会使经过身份验证的用户与 IdP 陷入无限的身份验证循环)。此自定义授权属性解决了该问题。

希望有帮助。

再见。

关于c# - asp.net mvc 上的自定义授权属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535430/

相关文章:

c# - List<T> 动态拼接

c# - 如何在 dot net 的融合 kafka 中使消费方法成为非阻塞

c# - 在 DNX PCL 中获取 ApplicationBasePath

c# - 名称 '“function”在当前上下文中不存在

asp.net mvc c# javascript web.config

asp.net-mvc - 我如何不允许对我的 Web 应用程序进行任何 Firefox 自定义?

javascript - 在没有 SPA 的情况下使用 BreezeJS

c# - 在 .GroupBy() 之后获取 List<SomeClass>

asp.net - 使用 aspnet core 自定义授权过滤器

javascript - 使用javascript在mvc路由的一部分中有效增加数字