[英]How to authorize access to static files based on claims
Static 文件可能需要根据文档对用户进行身份验证
根据具体声明,我无法找到任何有关限制对 static 文件的授权访问的信息。
例如,声明为“A”和“B”的用户可以访问文件夹 A 和 B,而只有声明“B”的用户只能访问文件夹 B
我将如何使用 .NET 6.0 / webAPI / static 文件“尽可能简单地”完成此操作?
来自链接示例;
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
您可以通过调用任何.Require...
方法来构建您想要的任何策略。 例如;
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireClaim("name", "value")
.Build();
});
请注意,回退策略适用于所有没有任何[Authorize]
元数据的端点。
相反,您可能需要编写一些中间件来检查每个路径的授权规则。 也许基于这个样本。
链接示例演示了一个有趣的概念。 授权是基于端点的,但是 static 文件中间件只是接管了响应,没有使用端点路由。 那么如果我们根据文件提供者生成我们自己的端点元数据呢?
.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");
});
当然,您可以通过 map 到 controller 的虚拟路径。
目前没有内置的方法来保护 wwwroot 目录,我认为你可以暴露一个端点,然后在端点中进行判断,这是一个非常简单的方法,如你所料,在你的问题中,你想访问 static 文件A
only user with claims A
,我在这里写了一个类似的demo,希望它能帮助你解决你的问题。
首先,我在wwwroot
中有一个名为“AAA”的 static 文件。
我在这里使用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);
然后我暴露一个端点来获取static路径然后做判断:
//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
}
}
}
看法
//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>
//.......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.