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

时间:2019-10-18 05:10:23

标签: asp.net-identity asp.net-core-3.0

我已在ASP.NET Core 3.0项目中自定义了身份,因为此链接文档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?}");
        });
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

查看您的代码,我注意到您已经切换了语句。对于您的情况,UseAuthorization授权匿名用户,然后在UseAuthentication中标识该用户。

请注意,将UseRequestLocalization放在UseRouting之前不起作用。因此顺序应为:

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