Home > Mobile >  Identity - How to redirect a user who is signed in
Identity - How to redirect a user who is signed in

Time:04-05

I need to know how to redirect a user if they are signed in to my app. There are 2 parts to my problem:

  1. Set the default page to /Account/Login
  2. If the user is already signed in (Remember Me check box is checked), then redirect to BookDetails.cs controller

I have already solved problem 1 by adding the following code to Program.cs: builder.Services.AddControllersWithViews().AddRazorPagesOptions(options => { options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "")})

I know how to check if the user is currently signed in. If I wanted to check if the user is currently signed in from BookDetailsController I would include the following code in the controller file:

...
private readonly SignInManager<IdentityUser> _signInManager;

public BookDetailsController(BookClubBookDetailsContext context, SignInManager<IdentityUser> signInManager)
{
   _signInManager = signInManager;
   _context = context;
}

...

My problem is where exactly do I put in the code for problem 2? Is it good practice if I put a redirect in /Account/Login, or should I put it in Program.cs?

CodePudding user response:

To redirect after login, simply you update your login method this way in AccountController

public async Task<IActionResult> Login(string returnUrl = null)
{
   //do sign in
   //if success then redirect
   if(!string.IsNullOrEmpty(returnUrl))
   {
      Redirect(returnUrl);
   }
}

if you are using page, check /account/login.cshrml.cs

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
   returnUrl ??= Url.Content("~/");

   //signIn using SignInManager
   

   if (result.Succeeded)
   {
       //if redirected from other site 
       //return Redirect(returnUrl);

       //Same site
       return LocalRedirect(returnUrl);
   }
}

CodePudding user response:

Try this:

   public class HomeController : Controller
   {

      private readonly SignInManager<IdentityUser> _manager;

      public HomeController
      (
         SignInManager<IdentityUser> manager
      )
      {
         _manager = manager;
      }

      [HttpGet]
      [AllowAnonymous]
      [Route("")]
      [Route("Home")]
      [Route("Index")]
      [Route("Home/Index")]
      public IActionResult Index()
      {
         if (_manager.IsSignedIn(User))
         {
            return View("1");
         }
         else
         {
            return View("0");
         }
      }
    }

The SignInManager will help you determine if the user is authenticated.

  • Related