首页 > 解决方案 > 带有 Identity Server 的 ASP.NET Core 授权权限访问文件夹

问题描述

在我的 ASP.NET Core 项目中,我与 Identity Server 集成。因此,用户必须登录 Identity Server,然后才能访问应用程序。

设计部门给了我一些 HTML5 的静态页面来发布,但只有经过身份验证的人或具有特定角色的人才能看到这些页面。

我想用旧web.config的来保护这个文件夹,比如

<location path="subdir1">
    <system.web>
        <authorization>
            <allow users ="*" />
        </authorization>
    </system.web>
</location>

但它也不起作用,因为我想使用角色而不是用户。

任何想法?

更新

一个快速的解决方案是在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?}");
    });
}

该目录html位于项目的根目录中。该文件夹受到保护,但网站的其余部分无法读取该wwwroot文件夹,例如我的主页如下所示:

在此处输入图像描述

我可以在 Devtool 中看到所有文件wwwroot都无法访问

在此处输入图像描述

标签: c#asp.net-coreidentityserver4

解决方案


我了解您的要求,但 ID4 令牌提供程序不能那样工作。根据我的理解,AuthenticationAuthorization是两个不同的任务,IdS4 只负责Authentication验证凭证并提供Access/Identity带有额外 required 的令牌claims。因此,如果您想authorize请求,那么您应该实现自己的逻辑(您可以为此目的创建自己的服务或在 API 中编写逻辑)。

对于授权,我强烈建议在您的 .NET 核心应用程序中使用基于策略的授权。

请同时查看Microsoft 的文档。

快乐编码!


推荐阅读