简体   繁体   English

如何使用ASP.NET MVC将安全权限应用于静态文件?

[英]How to apply security permissions to static files with ASP.NET MVC?

I'm trying to use ASP.NET MVC to have a web app that will take details about a parent item and allow uploads and sharing of files which are associated with and stored under the name of the parent item. 我正在尝试使用ASP.NET MVC来创建一个Web应用程序,该应用程序将包含有关父项的详细信息,并允许上传和共享与父项的名称相关联并存储在其下的文件。

The files I want to protect are stored in this way: ~/Files/{Item-GUID}/{Filename}.{ext} 我要保护的文件以这种方式存储:〜/ Files / {Item-GUID} / {Filename}。{ext}

The Item-Guid can be used to query the db for security permissions for the item. Item-Guid可用于向db查询该项目的安全权限。 (users are logged as AD SIDs) (用户被记录为AD SID)

I need to know how to have ASP.Net respond to file requests for these files in the path ~/Files/ and use the /Item-GUID/ to check security permissions before serving the file to the user, and throw authentication errors if the user is not logged in or does not have access to the parent item. 我需要知道如何让ASP.Net在〜/ Files /路径中响应这些文件的文件请求,并使用/ Item-GUID /在向用户提供文件之前检查安全权限,如果用户未登录或无法访问父项。

I would appreciate any links or advice on where should I start here. 我希望从此处开始的任何链接或建议,我将不胜感激。 Thanks In Advance. 提前致谢。

I use often create a custom permission class that derives from the AuthorizeAttribute class. 我经常使用创建自AuthorizeAttribute类派生的自定义权限类。 This is one way you can create a custom permissions filter on any controller action. 这是您可以在任何控制器操作上创建自定义权限过滤器的一种方法。

public MyPermissionsFilter : AuthorizeAttribute
{
    private readonly string _permissionName;

    public PermissionsFilter(string permissionName)
    {
        _permissionName = permissionName;
    }
}

Override the OnAuthorization method. 重写OnAuthorization方法。

public override void OnAuthorization(AuthorizationContext filterContext)
{
    //Perform Check with _permissionName
   //Redirect to error / unauthorised
}

Then decorate your controller action. 然后装饰您的控制器动作。

[HttpPost]
[PermissionsFilter("PermissionName")]
public void SaveFile(HttpPostedFileBase file)
{
  //Do file stuff
}

I hope that's what you want and is of some help. 我希望这是您想要的,对您有所帮助。

Addition : I've renamed GetFile to SaveFile.. and this is what is should have been. 另外:我已经将GetFile重命名为SaveFile ..,这应该是这样。

I've also been thinking about this again and it may not be the best solution for you. 我也一直在考虑这个问题,它可能不是您的最佳解决方案。 If you need to check a users permissions to access a single file based upon it's GUID, you might be better having the security check called in the SaveFile method that receives the file base parameter. 如果您需要根据GUID来检查用户访问单个文件的权限,则最好在接收FileBase参数的SaveFile方法中调用安全检查。 You can get the guid from the file name then to pass to the permissions check. 您可以从文件名获取GUID,然后传递给权限检查。 If it fails then simply redirect to the appropriate view. 如果失败,则只需重定向到适当的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM