Search code examples
c#razorasp.net-identity

Redirect on authentication based on user profile


I'm trying to get to grips with Razor pages (my previous experience is with web forms), and I'm running into difficulties with setting up a redirect after a user has logged in.

What I want to do is to look at some data about the user, and then redirect to a specific page based on the information.

In the default template provided by VS these lines of code handle the sign in:

var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");
    return LocalRedirect(Url.GetLocalUrl(returnUrl));
}

I tried using a UserManager instance to get information about the logged in user, but it doesn't work (it just returns null).

var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");
    var name = _userManager.GetUserName(HttpContext.User); //Returns null
    return LocalRedirect(Url.GetLocalUrl(returnUrl));
}

I'm guessing this is because the authentication cookie isn't set until the redirect page is loaded? (If I query the SignInManager immediately after result.Succeeded, it tells me the user isn't logged in).

Any pointers about the best technique for getting it to do what I want it to do would be much appreciated. Not entirely convinced the Razor pages documentation is up to scratch!


Solution

  • You are correct in saying that cookie is not set until the page is reloaded.

    However you are close - you already know the username - it is in Input.Email. Despite the confusing name of the variable, _signInManager.PasswordSignInAsync takes username, password and a bool (MSDN).

    So to get the full user object you need to use FindByNameAsync method on user manager:

    var userObject = await _userManager.FindByNameAsync(Input.Email);
    

    and then do whatever you need to do to decide where to redirect.