仅授权控制器允许在.net Core中进行匿名访问

我在.net核心Web应用程序中具有设置标识,并像这样将某个控制器标记为已授权。

[Authorize(Roles = "Partner")]
public class ClaimsController : Controller
{
    [Authorize(Roles = "Partner")]
    public IactionResult Index()
    {
        var authenticated = User.Identity.IsAuthenticated;
        //authenticated is false - but this view still loads?!
        return View();          
    }
}

因此,只有合作伙伴角色的用户才有权访问。但是,根本没有登录的用户可以加载并查看Claims控制器上的Index视图。。我可以检查是否有人登录并通过以下方式显式检查角色用户:用户经理,但是这些属性肯定可以起作用吗?

在core 3的startup.cs中是否还需要其他东西?这是我的startup.cs文件。

public class Startup
{
    private readonly IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application,visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        var connstring = _config.getconnectionString("HP_RBS_Database");

        //we can create our own role and derive from IdentityRole
        services.AddIdentity<UserLogin,IdentityRole>(x =>
        {
            x.User.RequireUniqueEmail = true;
            //set password rules in here..
        })  //specify where we store identity data
        .AddEntityFrameworkStores<HP_RBS_Context>();

        services.AddMvc();          
        services.AddRazorPages();
        services.AddControllersWithViews().AddRazorRuntimeCompilation();
        services.AddDbContext<HP_RBS_Context>(x =>
            {
                x.UseSqlServer(connstring);
            });

        services.AddTransient<HPPartnerPortalSeeder>();
        services.AddScoped<IHP_RBS_Repository,HP_RBS_Repository>();
        services.AddAuthentication();
        services.AddAuthorization();


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticfiles();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseRouting();
        app.UseEndpoints(x =>
        {
            x.MapControllerRoute("Default","{controller}/{action}/{id?}",new { controller = "Home",action = "Index" });
        });
    }
}
xianjian3 回答:仅授权控制器允许在.net Core中进行匿名访问

UseAuthenticationUseAuthorization的呼叫必须放在UseRoutingUseEndpoints之间:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(x =>
{
    x.MapControllerRoute("Default","{controller}/{action}/{id?}",new { controller = "Home",action = "Index" });
});

将这些呼叫放在 之前UseRouting时,UseAuthorization呼叫有点无操作。它检查是否已选择一个端点,但是还没有发生。选择过程是由接下来运行的UseRouting调用执行的,为时已晚。

不幸的是,这意味着MVC端点就像授权成功一样运行,即使它根本没有执行。这是ASP.NET Core 3.0.0发行版中的一个已知问题,已在3.0.1发行版中修复。

本文链接:https://www.f2er.com/3109643.html

大家都在问