[play-2.5.14 Java] CSRF Unauthorized

622 views
Skip to first unread message

Enrico Morelli

unread,
Apr 27, 2017, 4:44:39 AM4/27/17
to Play Framework
I followed the Play documentation to implement the CSRF check, but when I try to submit a form I receive an Unauthorized You must be authenticated to access this page.

I created a Filters class:

Enter code here...import play.http.DefaultHttpFilters;
import play.mvc.EssentialFilter;
import play.filters.csrf.CSRFFilter;
import javax.inject.Inject;

public class Filters extends DefaultHttpFilters {
   
@Inject
   
public Filters(CSRFFilter csrfFilter) {
       
super(csrfFilter);
   
}
}

I add filters to my build.sbt and enable it on applications.conf.

So in my login form I add

  @helper.form(routes.Application.authenticate(), 'class -> "form-signin" ) {
  @helper.CSRF.formField

In my controller i tryed:

@AddCSRFToken
   
public Result login() {
       
return ok(login.render("Login"));
   
}

@RequireCSRFCheck
   
public Result authenticate() {
       
DynamicForm requestData = formFactory.form().bindFromRequest();
       
...
       
...
}

Forms without the CSRF token give the same error.

If I reload the login page I'm able to enter in my application, but when I logout I receive again the error

public Result logout() {
        session
().clear();
       
return login();
   
}

So, how can solve the problem? Can I've form with and without CSRF?

Thanks

Will Sargent

unread,
Apr 27, 2017, 8:23:51 PM4/27/17
to Play Framework
When you logout, you need to clear the cookie and re-render the page.  So your logout should not be 

return login();

which is a 200, but instead should be a 303 or 307 Redirect:

return Redirect(routes.MyController.login());

Generally, any time you clear a session you should redirect, and that will ensure the browser sees the new cookie settings.

Greg Methvin

unread,
Apr 27, 2017, 9:48:58 PM4/27/17
to play-framework
You shouldn't be using the per-action annotations if you are using the CSRF filter. Just follow the instructions in the global CSRF filter section: https://www.playframework.com/documentation/2.5.x/JavaCsrf#Applying-a-global-CSRF-filter. There are no other changes needed to your actions. The filter will validate all POST requests.

--
You received this message because you are subscribed to the Google Groups "Play Framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framework+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/play-framework/339526a6-80fb-482a-a887-4e3d31d9b6cd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Greg Methvin
Tech Lead - Play Framework

Enrico Morelli

unread,
Apr 28, 2017, 3:56:42 AM4/28/17
to Play Framework

Thank to all. Following yours suggestions all works fine.
Reply all
Reply to author
Forward
0 new messages