Redirect user to original url after login in asp net core

Опубликовано: 15 Сентябрь 2024
на канале: kudvenkat
103k
784

How to redirect the user to the original requested URL after a successful login.

ReturnUrl in ASP.NET Core

Text version of the video


Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.


Slides


ASP.NET Core Text Articles & Slides


ASP.NET Core Tutorial


Angular, JavaScript, jQuery, Dot Net & SQL Playlists


What happens when we try to navigate to a URL, to which we do not have access

By default, ASP.NET Core redirects to the Login URL with ReturnUrl query string parameter. The URL that we were trying to access will be the value of the ReturnUrl query string parameter.

ReturnUrl Query String Example

In this example, ReturnUrl is set to ReturnUrl=/home/create. I was trying to Create a New Employee by navigating to /home/create without first signing in. Since I do not have access to /home/create until I login, ASP.NET core redirected to the login URL which is /Account/Login with the query string parameter ReturnUrl



The characters %2F are the encoded charactes for a forward slash (/). To decode these chracters in the URL, you may use the following website.


Redirect to ReturnUrl after Login

ASP.NET Core model binding automatically maps the value
from the URL query string parameter ReturnUrl
to the Login() action method parameter returnUrl
ASP.NET Core Redirect(returnUrl) method, redirects the user to the specified returnUrl

[HttpPost]
[AllowAnonymous]
public IActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var result = signInManager.PasswordSignInAsync(model.Email,
model.Password, model.RememberMe, false);

if (result.Succeeded)
{
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("index", "home");
}
}

ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}

return View(model);
}

There is a serious flaw in the way we have used the ReturnUrl query string parameter. This opens a serious security hole with in our application which is commonly known as open redirect vulnerability.

Next video : What is open redirect vulnerability and how to fix it in asp.net core