Static files can require the user to be authenticated as per documentation
I have not been able to find any info on restricting authorized access to static files, according to specific claims.
E.g. users with claims "A" and "B" have access to folder A and B, where as users with only claim "B" only have access to folder B
How would I accomplish this "as easy as possible" with asp.net 6.0?
CodePudding user response:
From the linked example;
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
You could build any policy you want, by calling any of the .Require...
methods. eg;
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireClaim("name", "value")
.Build();
});
Note that the fallback policy applies to all endpoints that don't have any [Authorize]
metadata.
Instead, you will probably need to write some middleware to check your authorization rule for each path. Perhaps based on this sample.
CodePudding user response:
Currently there is no built-in way to secure wwwroot directories, I think you can expose an endpoint, and then make judgments in the endpoint, This is a very simple method as you expected, in your question, you want to access static file A
only user with claims A
,I write a similar demo here, hope it can help you to solve your problem.
First I have a static file named "AAA" in wwwroot
.
I use Asp.Net Core Identity
here, Now I am logged in as a user, Then I add claim to this user.
//the claim's type and value is the same with static file name
Claim claim = new Claim("AAA", "AAA");
await _userManager.AddClaimAsync(user,claim);
Then I expose an endpoint to get the static path then do judgments :
//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
}
}
}
View
//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>
//.......