1

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

        }
    }
6
  • So I am assuming that when you login it just leaves you on login page? Commented Jan 6, 2021 at 20:25
  • @janzen Yes it just leaves me on login page Commented Jan 6, 2021 at 20:26
  • Do you have an endpoint or maproute set in the Configure method of Startup.cs? If so, add that to the question. Commented Jan 6, 2021 at 20:27
  • @janzen Okey I added it Commented Jan 6, 2021 at 20:30
  • 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? Commented Jan 6, 2021 at 20:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer but unfortunately this didn't fix my problem :(
@yigit.gok, ok, you're welcome, I didn't know your ajax.
0

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.

Comments

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.