【问题标题】:ASP.NET Core 3.0 - Identity Customization IssueASP.NET Core 3.0 - 身份自定义问题
【发布时间】:2020-02-15 01:33:24
【问题描述】:

我在 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?}");
        });
    }
}

【问题讨论】:

  • 你能显示你的 Startup.Configure 中的代码吗?
  • @RuardvanElburg 非常感谢您的友好回复!我已将 Startup.cs 代码添加到我的问题中

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


【解决方案1】:

问题在于使用语句的顺序。请查看order here

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

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

附带说明,当您将UseRequestLocalization 放在UseRouting 之前时,它不起作用。所以顺序应该是:

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

【讨论】:

  • 非常感谢您的支持,问题已按照您的指示解决。
猜你喜欢
  • 2020-01-24
  • 2020-10-24
  • 1970-01-01
  • 2017-02-15
  • 2021-02-11
  • 2016-07-05
  • 2018-11-13
相关资源
最近更新 更多