ASP.NET Core 3.1 [Authorize]属性重定向到登录,即使对于已登录的用户

问题描述

我有一个ASP.NET Core沙箱项目。 我添加IdentityDbContext注册页面工作正常。登录/注销页面工作正常。 (可以通过为SignInManager.IsSignedIn(User)用户显示的html看到)

我有一个标有[Authorize]的控制器:

[Authorize]
public class MyTestController : Controller
{
    ...
}

当我第一次尝试导航到它时-它可以正常工作(重定向登录页面

但成功登录后,它将再次重定向回具有相同链接登录https://localhost:44359/Identity/Account/Login?ReturnUrl=%2FMyTest

这是我来自Startup.cs代码

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddRazorPages().AddRazorRuntimeCompilation();
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                // Use the default property (Pascal) casing
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddDbContext<MyAppContext>(options => options.UsesqlServer(Configuration.GetConnectionString("Default")));
            services.AddDefaultIdentity<IdentityUser>(options =>
                {
                    options.Password.requiredigit = false;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = false;
                })
                .AddEntityFrameworkStores<MyAppContext>();

            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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

以前,我已经为登录,注销和注册添加了支架式身份项目。 没有[Authorize]的控制器效果很好。

解决方法

在我看来,您的中间件顺序不正确。 ASP.NET需要知道是否首先对用户进行身份验证,以便确定用户是否已获得请求的授权。尝试交换这两个:

    app.UseAuthentication();
    app.UseAuthorization();

Microsoft关于此主题的文档:Configure Identity