1
votes

I'm using [Authorize] attribute in asp.net core mvc first time. But I can't redirect to my index page when user logins correctly. I can trigger the "Index" action of "Panel" controller but its view is not loading. Nothing happens when break point comes here:

**(Teacher Area PanelController)**
public IActionResult Index()
        {
            return View();
        }

Here is my Login method:

**(AccountController)**
[HttpPost]
        public async Task<IActionResult> Login(LoginRequest loginRequest)
        {
            if (_loginService.Login(loginRequest))
            {
                var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, loginRequest.Mail)
            };
                var userIdentity = new ClaimsIdentity(claims, "Login");
                ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
                await HttpContext.SignInAsync(principal);
                return RedirectToAction("Index","Panel",new { area="Teacher" });
            }
            return View();
        }

Authorize works properly. After I login via my Login method, I can access methods under the [Authorize] attribute by entering link myself. I searched for the solution many times but I couldn't anything about it.

Thx...

Edit: Here is my ConfigureServices method:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(opt => opt.EnableEndpointRouting = false);
            services.AddRazorPages();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Account/Login";
        });
            services.AddSingleton<IFileProvider>(
            new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
            services.AddControllersWithViews();
            services.AddSingleton<IUserService, UserService>();
            services.AddSingleton<ILoginService, LoginService>();
            services.AddSingleton<IUserRepository, UserRepository>();
        }

and Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseAuthentication();
            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.UseRouting();
            app.UseAuthorization();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}");
                routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}");
            });

        }
    }
2
So I am assuming that when you login it just leaves you on login page? - jaabh
@janzen Yes it just leaves me on login page - yigit.gok
Do you have an endpoint or maproute set in the Configure method of Startup.cs? If so, add that to the question. - jaabh
@janzen Okey I added it - yigit.gok
I would suggest, if you want to redirect to "/Teacher/Panel/Index" then maybe add that in MapRoute section. Also you have a breakpoint on Panel/Index, add a breakpoint to the login method also. And be more descriptive on what happens when the Panel/Index breakpoint is hit.Is there an error, does it return the view? - jaabh

2 Answers

1
votes

You can try to remove exists in MapRoute. This is the official description:

In the preceding code, exists applies a constraint that the route must match an area.

RedirectToAction will generate route according to the route template.

In addition, you can refer to this document.

0
votes

Problem solved. I was sending the login info with ajax. When I remove ajax and send with only form action, my problem is solved. Thanks for answers.