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