该 url 必须以某种方式通过控制器或 httpmodule 或 thingIdontknow 才能被授权查看该文件。这些权限可能每天都在变化,因此需要经常检查文件的权限。
你不知道的东西有个名字。它称为授权操作过滤器。
首先让我们假设您已经注册了一个自定义路由来提供这些文件:
routes.MapRoute(
"MyImagesRoute",
"files/{id}/{name}",
new { controller = "Files", action = "Index" }
// TODO: you could constrain the id parameter to be a GUID.
// Just Google for a Regex that will match a GUID pattern and put here
// as route constraint
);
然后当然是相应的控制器来为他们服务:
public class FilesController: Controller
{
public ActionResult Index(Guid guid, string name)
{
var path = @"C:\files";
var file = Path.Combine(path, guid.ToString(), name);
file = Path.GetFullPath(file);
if (!file.StartsWith(path))
{
// someone tried to be smart and send
// files/{Guid}/..\..\creditcard.pdf as parameter
throw new HttpException(403, "Forbidden");
}
// TODO: adjust the mime type based on the extension
return File(file, "image/png");
}
}
不幸的是,在这个阶段没有什么可以阻止用户 ALPHA 请求用户 BETA 的文件,对吧?这就是你想要处理的场景,不是吗?
所以让我们编写一个自定义的 Authorize 属性来保护这个控制器动作:
public class MyAuthorizeAttribute: AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated or doesn't have
// permissions to access this controller action
return false;
}
// at this stage we know that there's some user authenticated
// Let's get the Guid now from our route:
var routeData = httpContext.Request.RequestContext.RouteData;
var id = routeData.Values["id"] as string;
Guid guid;
if (!Guid.TryParse(id, out guid))
{
// invalid Guid => no need to continue any further, just deny access
return false;
}
// Now we've got the GUID that this user is requesting
// Let's see who this user is:
string username = httpContext.User.Identity.Name;
// and finally ensure that this user
// is actually the owner of the folder
return IsAuthorized(username, guid);
}
private bool IsAuthorized(string username, Guid guid)
{
// You know what to do here: hit your data store to verify
// that the currently authenticated username is actually
// the owner of this GUID
throw new NotImplementedException();
}
}
然后让我们用这个授权属性来装饰我们的控制器动作:
public class FilesController: Controller
{
[MyAuthorize]
public ActionResult Index(Guid guid, string name)
{
// at this stage we know that the currently authenticated user
// is authorized to access the file.
var path = @"C:\files";
var file = Path.Combine(path, guid.ToString(), name);
file = Path.GetFullPath(file);
if (!file.StartsWith(path))
{
// someone tried to be smart and send
// files/{Guid}/..\..\creditcard.pdf as parameter
throw new HttpException(403, "Forbidden");
}
var file = Path.Combine(@"c:\files", guid.ToString(), name);
// TODO: adjust the mime type based on the extension
return File(file, "image/png");
}
}