ASP.NET Core 3.0 - 身份定制问题

ASP.NET Core 3.0 - Identity Customization Issue

我在 ASP.NET Core 3.0 项目中定制了 Identity 作为这个 link 文档 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.0 它在注册、登录和 User.Identity.Name 属性 方面工作正常成功返回用户名,但任何控制器都有 [Authorize] 属性重定向到登录页面!

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<DatabaseContext>(cfg => {
            cfg.UseSqlServer(Configuration.GetConnectionString("PrimaryConnection"));
        });

        services.AddIdentity<AppUser, AppRole>(Options =>
        {
            Options.User.RequireUniqueEmail = true;
        }).AddEntityFrameworkStores<DatabaseContext>();

        services.AddScoped<UserRepository>();

        services.AddControllersWithViews();

        services.AddLocalization(o => {
            o.ResourcesPath = "Resources";
        });

        services.AddMvc()
            .AddViewLocalization(o => {
                o.ResourcesPath = "Resources";
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        services.Configure<RequestLocalizationOptions>(o => {
            List<CultureInfo> supportedCultures = new List<CultureInfo>()
            {
                new CultureInfo("en-US"),
                new CultureInfo("ar-EG")
            };

            o.DefaultRequestCulture = new RequestCulture("en-US");
            o.SupportedCultures = supportedCultures;
            o.SupportedUICultures = supportedCultures;
        });

        services.ConfigureApplicationCookie(options => {
            options.LoginPath = new PathString("/Home/Login");
            options.LogoutPath = new PathString("/Home/Logout");
            options.AccessDeniedPath = new PathString("/Error/AccessDenied");
            options.Cookie.Name = "Cookie";
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(720);
            options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
            options.SlidingExpiration = true;
        });
    }

    // 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.UseCookiePolicy();

        IOptions<RequestLocalizationOptions> options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);

        app.UseRouting();

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

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

问题是使用语句的顺序。请检查 order here.

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

查看您的代码,我注意到您已经切换了语句。在您的情况下 UseAuthorization 授权匿名用户,之后您在 UseAuthentication.

中识别用户

附带说明一下,UseRequestLocalization 放在 UseRouting 之前不起作用。所以顺序应该是:

app.UseRouting();
app.UseRequestLocalization(options.Value);
app.UseAuthentication();
app.UseAuthorization();