Cookie Authentication not redirecting after user login in asp.net core 3

644 Views Asked by At

I can't quite wrap my head around this problem, When a user navigates to the admin URL, they are redirected to admin specific account/login page (located in admin Area's folder). But when the admin logs into the admin controller that is decorated with the [Authorize(Roles = "Admin", AuthenticationSchemes = "Backend")] attribute, the page just reloads with returnUrl. It seems like the application does not recognize the logged-in user to grant access to the admin controller actions, can't figure out why. Please help!

Admin Controller

[Authorize(Roles = "Admin", AuthenticationSchemes = "Backend")]
[Area("Admin")] 
public class AdminController : Controller
{
  private readonly IAdminRepository _adminInterface;
  private readonly UserManager<AppUser> _userManager;
  private readonly RoleManager<IdentityRole> _roleManager;

  public AdminController(IAdminRepository adminInterface, UserManager<AppUser> userManager, 
    RoleManager<IdentityRole> roleManager)
 {
    _adminInterface = adminInterface;
    _userManager = userManager;
    _roleManager = roleManager;
 }

 public IActionResult Index()
 {
    return View();
 }

}

Account Controller

[Area("Admin")]
public class AccountController : Controller
{
private readonly SignInManager<AppUser> _signInManager;
private readonly UserManager<AppUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;

public AccountController(SignInManager<AppUser> signInManager, 
    UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
{
    _signInManager = signInManager;
    _userManager = userManager;
    _roleManager = roleManager;
}

[HttpGet]
public IActionResult Login()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model, string ReturnUrl)
{
    if(ModelState.IsValid)
    {
        var user = await _userManager.FindByNameAsync(model.Username);
        if(user != null && !(await _userManager.IsInRoleAsync(user, "Admin")))
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt");
            return View(model);
        }
        if(user != null && !user.EmailConfirmed && (await _userManager.CheckPasswordAsync(user, model.Password)))
        {
            ModelState.AddModelError(string.Empty, "Confirm Email Address");
            return View(model);
        }

        var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, true);
        if(result.Succeeded)
        {
            if(!string.IsNullOrEmpty(ReturnUrl) && Url.IsLocalUrl(ReturnUrl))
            {
                return Redirect(ReturnUrl);
            }
            else
            {
                return RedirectToAction("index", "admin");
            } 
        }
        ModelState.AddModelError(string.Empty, "Invalid login attempt");
    }
    return View(model);
}
}

Dashboard Controller

[Area("Admin")]
[Authorize(Role = "Admin", AuthenticationSchemes = "Backend")]
public class DashboardController : Controller
{
   public IActionResult Index()
   {
     return View();
   }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
 {
    services.AddControllersWithViews(); 


    services.AddIdentity<AppUser, IdentityRole>(options =>
    {
        options.Password.RequiredUniqueChars = 3;
        options.Password.RequiredLength = 8;
        options.User.RequireUniqueEmail = true;
    }) 
    .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddScoped<IAdminRepository, AdminRepository>();
    services.AddAuthentication()
    .AddCookie("Backend", options =>
    {
        options.Cookie.Name = "Backend";
        options.LoginPath = new PathString("/admin/account/login/");
        options.LogoutPath = new PathString("/admin/account/logout/"); 
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.LoginPath = new PathString("/account/login/");
    }); 

 }



public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseStaticFiles();
    app.UseHttpsRedirection();
    app.UseRouting();


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

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
            name: "AllAreas",
            pattern: "{area:exists}/{controller=admin}/{action=index}/{id?}");

            endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=home}/{action=index}/{id?}");
       }); 
   }
0

There are 0 best solutions below