Preventing Redirect Attacks in ASP.NET Core 2.0

Problem

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 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 to configure services and middleware for MVC:

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

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: https://github.com/TahirNaushad/Fiver.Security.Redirects

Leave a Reply