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?
You can use the Referer
header, or explicitly carry the return url in your authenticate action:
Referer
headerdef 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)
}
}
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…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With