iProblem
How to prevent open redirect attacks in ASP.NET Core.
Solution
When your controllers redirect to another location based on user input (e.g. via a query string), it is important to ensure that the location is not malicious and prevent open redirect attacks. The simplest way to ensure this is by examining the URL provided by the user. Framework provides couple of ways to achieve this,
- LocalRedirect() method redirects to local URL or throws an exception.
- IsLocalUrl() method returns true for local URLs.
Create an empty project and update Startup class to configure the services and middleware for MVC.
- public class Startup
- {
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddMvc();
- }
-
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseExceptionHandler("/Home/Exception");
- app.UseMvcWithDefaultRoute();
- }
- }
Add a controller to illustrate LocalRedirect() and IsLocalUrl() methods,
- public class HomeController : Controller
- {
- public IActionResult Index() => Content("Home");
- public IActionResult About() => Content("About");
- public IActionResult Exception() => Content("Exception");
- public IActionResult Error() => Content("Error");
-
- public IActionResult GoLocalRedirect(string url)
- => LocalRedirect(url);
-
- public IActionResult GoIsLocalUrl(string url)
- {
- if (Url.IsLocalUrl(url))
- return Redirect(url);
- else
- return RedirectToAction("Error", "Home");
- }
- }
You could browse to these paths to test the sample,
Path | Result |
/Home/GoLocalRedirect?url=/Home/About | About |
/Home/GoLocalRedirect?url= http://tahirnaushad.com | Exception |
/Home/GoIsLocalUrl?url=/Home/About | About |
/Home/GoIsLocalUrl?url=http://tahirnaushad.com | Error |
Source Code
GitHub