Preventing Redirect Attacks In ASP.NET Core 2.0

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.

Add a controller to illustrate LocalRedirect() and IsLocalUrl() methods,

You could browse to these paths to test the sample,

PathResult
/Home/GoLocalRedirect?url=/Home/AboutAbout
/Home/GoLocalRedirect?url= http://tahirnaushad.comException
/Home/GoIsLocalUrl?url=/Home/AboutAbout
/Home/GoIsLocalUrl?url=http://tahirnaushad.comError

Source Code

GitHub

Up Next
    Ebook Download
    View all
    Learn
    View all