如何根据声明授权对静态文件的访问



静态文件可以要求用户按照文档进行

认证我没有找到任何关于限制授权访问静态文件的信息,根据特定的声明。

。用户与索赔"one_answers";B"可以访问文件夹A和B,其中用户只要求"B"只能访问文件夹B

我该如何做到这一点"尽可能简单"?与。net 6.0/webAPI/静态文件?

目前没有内置的方法来保护wwwroot目录,我认为你可以暴露一个端点,然后在端点中做出判断,这是一个非常简单的方法,正如你所期望的,在你的问题中,你想访问静态文件A只有用户声称A,我在这里写了一个类似的演示,希望它能帮助你解决你的问题。

首先我有一个静态文件名为"AAA"inwwwroot.

我在这里使用Asp.Net Core Identity,现在我作为一个用户登录,然后我添加声明到这个用户。

//the claim's type and value is the same with static file name
Claim claim = new Claim("AAA", "AAA");
await _userManager.AddClaimAsync(user,claim);

然后我公开一个端点来获取静态路径,然后做判断:

//Add [Authorize] attribute, the controller can only be accessed when the user is logged in 
[Authorize]
public class TestController : Controller
{
//Pass in the name of the static file that needs to be accessed, and then use claim to authorize
public IActionResult Find(string path)
{
var value = IHttpContextAccessor.HttpContext.User.Claims.Where(e => e.Type == path ).Select(e => e.Value).FirstOrDefault();
if(value !=null && value == path) {
//authorize success
//read the static file and do what you want

}else{
//authorize fail
}
}
}
<<p>视图/strong>
//use asp-route-path="AAA" to pass the value of path
<a asp-controller="Test" asp-action="Find" asp-route-path="AAA">AAA</a>
<a asp-controller="Test" asp-action="Find" asp-route-path="BBB">BBB</a>
//.......

从链接的例子;

builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});

您可以通过调用任何.Require...方法来构建您想要的任何策略。例如,


builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireClaim("name", "value")
.Build();
});

注意,回退策略适用于所有没有任何[Authorize]元数据的端点。

相反,您可能需要编写一些中间件来检查每个路径的授权规则。也许基于这个示例。

链接的示例演示了一个有趣的概念。授权是基于端点的,但是静态文件中间件只是接管响应而不使用端点路由。那么,如果我们基于文件提供程序生成自己的端点元数据呢?

.Use((context, next) => { SetFileEndpoint(context, files, null); return next(context); });

这是可行的,但如果我们只是定义一个假端点呢?

app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles();
app.UseEndpoints(endpoints => {
endpoints.MapGet("static/pathA/**", 
async (context) => context.Response.StatusCode = 404)
.RequireAuthorization("PolicyA");
});

当然你可以将虚拟路径映射到控制器。

最新更新