How to properly use RedirectToAction()

572 Views Asked by At
    namespace AspWebAppTest.Controllers
    {
    public class AccountController : Controller
    {
    
    public IActionResult Login()
    {
        return View();
    }
    
    [HttpGet]
    public IActionResult Login(string userName, string password)
    {
        if (!string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password))
        {
            return RedirectToAction("Login");
        }

        
        ClaimsIdentity identity = null;
        bool isAuthenticated = false;

        if (userName == "Admin" && password == "pass")
        {

           
            identity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Role, "Admin")
            }, CookieAuthenticationDefaults.AuthenticationScheme);

            isAuthenticated = true;
        }
        if (isAuthenticated)
        {
            var principal = new ClaimsPrincipal(identity);

            var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

            return RedirectToAction("Mapping","Setting", "Home");
        }

        return View();
    }
    public IActionResult Logout()
    {
        var login = HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Login");
    }

}

}

I have this Cookie Authentication Controller for my tabs(Mapping, and Config). I'am using RedirectToAction() method to redirect my return view to access mapping and config tab once the user entered the correct password and username. My problem is, after I put the password and username nothing is happening. Am I using the wrong method?

Here is my startup.cs

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

enter image description here

1

There are 1 best solutions below

1
Richard Deeming On

The SignInAsync method returns a Task which will complete when the sign-in operation has succeeded.

Your code does not await this Task, so you're sending the redirection response before the user has been authenticated.

Make your actions async, and await the results of the Sign[In|Out]Async methods:

[HttpGet]
public async Task<IActionResult> Login(string userName, string password)
{
    ...
    if (isAuthenticated)
    {
        var principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

        return RedirectToAction("Mapping", "Setting", "Home");
    }

    return View();
}

public async Task<IActionResult) Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return RedirectToAction("Login");
}