“Security aware” action link?

前端 未结 4 1214
广开言路
广开言路 2020-12-04 11:54

How can I create a \"security aware\" action link that detects if a user is authorized to click (invoke) the action?
Hide link if user is not allowed to use that action.

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 12:19

    jfar's code worked for me for the most part, but I had to make some modifications for MVC4. This is the only method that had to change:

    private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false; // action does not exist so say yes - should we authorise this?!
    
        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);
    
        // run each auth filter until on fails
        // performance could be improved by some caching
        foreach (var filter in FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor))
        {
            var authFilter = filter.Instance as IAuthorizationFilter;
    
            if (authFilter == null)
                continue;
    
            authFilter.OnAuthorization(authContext);
    
            if (authContext.Result != null)
                return false;
        }
    
        return true;
    }
    

提交回复
热议问题