[英]How do I serve static files only to authorized users?
我有一組Excel電子表格,我只想在授權用戶的ASP.NET 5 webapp中提供這些電子表格。
非常感謝!
在.net核心中創建一個與wwwroot相同級別的專用目錄www,並使用以下代碼:
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[Authorize(Roles = "SomeRole")]
public IActionResult Performance()
{
return PhysicalFile(Path.Combine(_hostingEnvironment.ContentRootPath,
"www", "MyStaticFile.pdf"), "application/pdf");
}
基於以下答案(針對.netCore): 靜態文件授權
檢索文件時進行身份驗證檢查:
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
if (!context.Context.User.Identity.IsAuthenticated && context.Context.Request.Path.StartsWithSegments("/excelfiles"))
{
throw new Exception("Not authenticated");
}
}
});
如果您有登錄表單(Login.html),一個簡單的解決方案是,如果用戶未經過身份驗證並且他正在請求受保護資源(/ protected文件夾下的文件),則會將用戶重定向到登錄頁面。 在Startup.cs中,在Configure方法中插入以下代碼:
app.Use(async (context, next) =>
{
if (!context.User.Identity.IsAuthenticated && context.Request.Path.StartsWithSegments("/protected"))
{
context.Response.Redirect("/Login.html");
return;
}
await next.Invoke();
});
這是一個非常簡單的示例,但可以更改它以檢查特定角色,並且可以將代碼移出Startup.cs以獲得更大的靈活性。
app.Use(async (context, next) =>
{
if (!context.User.Identity.IsAuthenticated
&& context.Request.Path.StartsWithSegments("/excelfiles"))
{
throw new Exception("Not authenticated");
}
await next.Invoke();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.