Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Prevent CSRF in Play [2.0] Using Scala?

A lot of web frameworks have a standard setup for generating forms with auth tokens.

Do I have to create such measures manually, or does Play come with a build in means of prevening CSRF?

The documentation on the Play website doesn't seem to address this.

like image 477
Jacob Groundwater Avatar asked Mar 30 '12 03:03

Jacob Groundwater


3 Answers

I use the play2-authenticitytoken module:

The authenticity token is a way around one of the most serious internet security threats: CRSF attacks. It ensures that the client submitting a form is the one who received the page (and not a hacker who stole your session data).

How it works:

In a nutshell:

  1. on every form post, we add a hidden parameter containing a uuid
  2. the uuid is signed and its signature is stored in the session (which translated into a cookie)

When the user submits the form, we get: the uuid, the signature and the other form inputs.

  1. We sign the incoming uuid again
  2. Validation passes if the signatures match (session.sign=uuid.sign)

Should an attacker inject a different id, he will never figure how to generate the correct signature.

like image 121
Masahito Avatar answered Sep 19 '22 18:09

Masahito


For completeness sake, I have an example here in Scala for Play 2.0

  • https://github.com/jacobgroundwater/Scala-Play-CSRF

This method also uses the cookie + hidden-field approach.

Example Usage

Use the SessionKey action to help sign a form:

object Application extends Controller {
    def login = SessionKey{ (key,signature) => 
        Action { implicit request =>
            Ok( views.html.login(signature) ).withSession( key->signature )
        }
    }
}

When parsing forms use the following to check for the signature:

object Authenticator extends Controller {
    def login = ValidateForm{ 
        Action { implicit request =>
            Ok( views.html.index("You're Loggd In") )
        }
    }   
}
like image 40
Jacob Groundwater Avatar answered Sep 18 '22 18:09

Jacob Groundwater


Since Play 2.1 there's support for this in the framework. Nick Carroll wrote a nice little article on how to use it:

http://nickcarroll.me/2013/02/11/protect-your-play-application-with-the-csrf-filter/

like image 45
agabor Avatar answered Sep 22 '22 18:09

agabor