簡體   English   中英

如何根據聲明授權訪問static個文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM