问题
In my ASP.NET Core project, I have the integration with Identity Server. So, users have to login in Identity Server and then they have access to the application.
The design department gave me some static page in HTML5 to publish but only authenticated people or with a specific role can see those pages.
I thought to use the old web.config
to protect this folder like
<location path="subdir1">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>
but it doesn't work also because I want to use Roles instead of users.
Any idea?
Update
A quick solution is to add some setting in the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
const string cacheMaxAge = "604800";
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append(
"Cache-Control", $"public, max-age={cacheMaxAge}");
},
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "html")),
RequestPath = "/infographics"
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
The directory html
is in the project's root. The folder is protected but the rest of the website can't read the wwwroot
folder and for example my home page looks like that:
and I can see in the Devtool that all files under wwwroot
are not accessible
回答1:
I understand your requirement but the ID4 token provider doesn't work that way. As per my understanding, Authentication
and Authorization
are two different tasks and IdS4 is responsible for Authentication
only where it will just validate the credential and provide Access/Identity
token with additional required claims
. So if you want to authorize
request then you should implement your own logic(you can create your own service for that purpose or write your logic inside your API).
For authorization, I would strongly recommend using policy-based authorization in your .NET core app.
Please take look at Microsoft's docs as well.
Happy Coding!
来源:https://stackoverflow.com/questions/65215275/asp-net-core-authorization-permission-access-folder-with-identity-server