代码之家  ›  专栏  ›  技术社区  ›  Larry Lustig

我可以通过编程检查用户是否被授权使用给定的控制器方法吗?

  •  1
  • Larry Lustig  · 技术社区  · 6 年前

    [请注意,这个问题是关于dotnet core 1.1的]

    我有一个控制器方法在我的 ItemsController 类的属性如下,以限制管理员组中的用户访问方法的能力:

        [Authorize(Roles = @"MYDOMAIN\ThisApplicationAdmins")]
        [HttpDelete("/items/{itemsName}")]
        public ActionResult DeleteItem(string itemName)
        {
            // Dangerous code here.
        }
    

    这是正确的。

    此外,我还想删除应用程序中的红色x,它为无法访问该方法的用户触发此控制器方法。我知道我可以检查用户是否在正确的广告组中,但这需要我复制我的授权逻辑,并向我展示我将更新属性的可能性,而不是用户界面检查。

    是否存在查询ASP Dotnet Core以询问“用户x是否有权访问方法” ItemsController.DeleteItem() “这个问题是否由负责处理属性的中间件回答?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Pooja Suryawanshi    6 年前

    是的,您可以在UI和控制器之间的中间层检查特定用户是否可以访问请求的控制器。

    / 我们需要在我们的视图中的某个地方添加Async方法 /

    @if (await Url.HasAccessToController(urlActionContext))
    {
        <p>You have access</p>
    }
    

    方法的实施:

    public static async Task<bool> HasAccess(this IUrlHelper Helper, UrlActionContext ActionContext, string httpMethod = "GET" )
    {
    //U need to Implement this method as per your needs
    
        var httpContext = Helper.ActionContext.HttpContext;
    
        var routeValues = new RouteValueDictionary(ActionContext.Values);
        routeValues["action"] = ActionContext.Action;
        routeValues["controller"] = ActionContext.Controller;          
    
        var path = Helper.Action(ActionContext);
    
        var features = new FeatureCollection();
        features.Set<IHttpRequestFeature>(new HttpRequestFeature()
        {
            Method = httpMethod, 
            Path = path,
    
        });
    
        var ctx = new DefaultHttpContext(features);      
    
        var routeContext = new RouteContext(ctx);
    
        foreach (var entry in routeValues)
        {
            routeContext.RouteData.Values.Add(entry.Key, entry.Value);
        }
    
        var actionSelector = httpContext.RequestServices.GetRequiredService<IActionSelector>();
    
        var provider = httpContext.RequestServices.GetRequiredService<IActionDescriptorCollectionProvider>();       
        var actionDescriptors = actionSelector.SelectCandidates(routeContext);
    
        var actionDescriptor = actionSelector.SelectBestCandidate(routeContext, actionDescriptors);
    
        var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();
    
        var ok = await authService.AuthorizeAsync(httpContext.User, actionDescriptor, "YOUR_POLICY"); 
    
        return ok;
    
    }