Search code examples
c#entity-frameworkasp.net-core-mvccsrfcsrf-protection

Protecting from cross-site request forgery attacks


I am now learning a concept of ASP.NET Core development and during my learning I have found out from the following article that a webpage needs to be protected from unauthorized access in order to prever from Cross Site Request Forgery Attacks.

I have followed several tutorials and for my own (learning) application I have:

  • Implemented the [Authorize] decorator on the top of my Controller (in my case it was API controller)
  • In the actual POST, UPDATE methods I have implemented if (ModelState.IsValid) call to check, if necessary parameters have been passed
  • Used ViewModels instead of actual Models that are used in a database when communicating with a website (or API in this case).

I have the following three questions:

1) Is this approach sufficient in order to protect my website? As an authentication method I am using simple CookieAuthentification. Or in other words (as this might be too broad question), is this approach on a right track to dishearten possible attacker?

2) In my current setup (of using ViewModels instead of real models) is [ValidateAntiForgeryToken] necessary? If yes, what purpose it serves?

3) Now the question (which I am most interested in) is regarding ViewModels. How can ViewModels protect my website from unauthorized attacks? I do understand that in my ViewModel I can only expose variables/properties that I want user to have access to (and hide the rest), but how can it protect my website, when I still need to expose my ID (primary key) (as without ID I cannot imagine how one would do e.g. DELETE / UPDATE calls)?

Any help in this matter would be more than appreciated as I am still learning this subject.


Solution

  • Web site security is a complex issue. Protections should be implemented that are commensurate to the sensitivity of data requiring protection.

    1) Some level of Authentication is necessary to protect against an anonymous attack, where an attacker would have an infinite number of tries to get a successful attack.

    2) [ValidateAntiForgeryToken] is required for any data change. Without it you could have a user who has successful authenticated and been given a valid cookie, that is then stolen by a malicious actor who has compromised the browser being used by your valid user, and use that stolen cookie to make unwanted data changes.

    3) The use of ViewModels means that you have not exposed direct data calls to the database. Yes a malicious actor could modify data in undesirable ways, but is still limited to changes within the scope of your data layer. Without ViewModels it might be possible for an attacker to make changes that you never intended through SQL Injection. If you are using an ORM such as Entity Framework then the possibility of SQL Injection is less likely.