Search code examples
asp.net-identityasp.net-core-3.0

ASP.NET Core 3.0 - Identity Customization Issue


I have customized Identity in ASP.NET Core 3.0 project as this link documentation https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.0 it is working fine on registration, login and User.Identity.Name property returned user name successfully but any controllers has [Authorize] attribute redirect to login page!

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

Solution

  • The problem is the order of use statements. Please check the order here.

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

    Looking at your code I notice that you've switched the statements. In your case UseAuthorization authorizes the anonymous user, after which you identify the user in UseAuthentication.

    As a side note, UseRequestLocalization doesn't work when you place it before UseRouting. So the order should be:

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