0

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?}");
        });
    }
}
2
  • Can you show the code from your Startup.Configure? Commented Oct 18, 2019 at 8:07
  • @RuardvanElburg Thanks a lot for your kind reply! I have added Startup.cs code to my question Commented Oct 23, 2019 at 3:27

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your kind support, the issue has been resolved by following your instruction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.