Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Play! 2.0 with Security trait how do I redirect to the original URL after login?

With Play! framework 2.0, using the Security Trait:

If I let users browse to several parts of the site unauthenticated, but on certain actions they need to authenticate, how do I redirect them to their original url before authentication and not the same url for all?

It is a similar requirement to this question for Play! 1.x Playframework's Secure module is not redirecting to the original url after login.

However the flash parameter for the original url is not available in 2.0 as far as I can tell.

Basicaly the change I am looking for would be in the authenticate method handler

def authenticate = Action { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.login(formWithErrors)),
      user => Redirect(routes.Application.index).withSession(Security.username -> user._1)
    )
  }

Where some sort of Redirect(originalRequestUrl) would be handy.

Any ideas for a clean solution?

like image 507
flurdy Avatar asked Apr 18 '12 17:04

flurdy


1 Answers

You can use the Referer header, or explicitly carry the return url in your authenticate action:

Using the Referer header

def authenticate = Action { implicit request =>
  loginForm.bindFromRequest.fold(
    errors => BadRequest(html.login(errors)),
    user => {
      val returnUrl = request.headers.get(REFERER).getOrElse(routes.Application.index.url)
      Redirect(returnUrl).withSession(Security.username -> user._1)
    }
}

Carrying explicitly the return url

def authenticate(returnUrl: String) = Action { implicit request =>
  loginForm.bindFromRequest.fold(
    errors => BadRequest(html.login(errors, returnUrl)),
    user => Redirect(returnUrl).withSession(Security.username -> user._1)
  )
}

By using the Referer HTTP header you still have to handle the case where the browser doesn’t fill this header, and by carrying explicitly the return url as a parameter of your authenticate action you may have more boilerplate in your code handling with authentication…

like image 107
Julien Richard-Foy Avatar answered Sep 20 '22 22:09

Julien Richard-Foy