我是新的scala play framework.i想要重定向到登录页面,如果会话值找不到,用户尝试home或任何其他page.hope的url你理解我想要的东西。在scala play框架中如果用户尝试没有登录就转到主页然后显示错误。我不想显示这些错误,我希望该用户自动重定向到登录页面。提前获取帮助
答案 0 :(得分:2)
如果存在所需的会话值,您可以使用Global object检查每个请求,并在其他情况下重定向到登录页面。
这很容易实现,无论如何都无法向您展示Scala示例,因为我只使用Java,在我的情况下最简单的方法是(简化演示):
@Override
public Action onRequest(Http.Request request, Method method) {
if (request.cookie("logged_user") == null && !request.path().startsWith("/login")) {
return new Action.Simple() {
public Result call(Http.Context ctx) throws Throwable {
return temporaryRedirect("/login");
}
};
}
return super.onRequest(request, method);
}
答案 1 :(得分:0)
查看播放文档www.playframework.com/documentation/2.0.x/ScalaSecurity,您可以在此处获得如何使用安全特征执行授权的示例
答案 2 :(得分:0)
有很多方法可以做到这一点,这是一个选择问题。虽然我已经使我的个人会话管理松散耦合。
import play.api.mvc._
import play.api.Logger
/**
* Trait to convert cookie to something which makes sense literally.
* @tparam A Session Object type.
*/
trait DecryptSession[A] {
/**
* Retrieve the connected user email.
*/
protected final def username(request: RequestHeader): Option[String] = request.session.get(sessionId)
/**
* Takes the parameter obtained from cookie (after decyphering) and then converts it to type A
* @param the string obtained from Session Cookie
* @return Left(err) err: is the error string if something is wrong with Cookie. Right(Option[A])
*/
protected def fromSession(param: String): Either[String, A]
/**
* Saves a session object and returns a Session tuple containign key-value pair of
* Cookie-key and Cookie-value. This can be directly used for result.
* Example:
* {{{
* Ok("hey").withNewSession(toSession(userObject))
* }}}
*/
def toSession(param: A): (String, String)
protected val sessionId = "sessionId";
}
/**
* Provide security features
*/
trait WebSecurity[A] extends DecryptSession[A] {
import play.api.mvc.BodyParsers._
import views._
/**
* Redirect to login if the user in not authorized.
*/
private def onUnauthorized(request: RequestHeader) =
play.api.mvc.Results.Redirect(controllers.routes.Assets.at("public/signup.html"))
/**
* Checks if the user is a authenticated/logged in User. If yes, then executes "f" body.
* Else does action based on onAuthFailure.withNewSession
*
* @tparam T the content type
* @param bodyParser the `BodyParser` to use to parse the request body
* @param onAuthFailure function used to generate alternative result if the user is not authenticated
* @param f Body. It gets User and request object as arguments and returns a Result. Just like any other Action
*/
def GeneralFilter[T](bodyParser: BodyParser[T] = parse.anyContent)(onAuthFailure: RequestHeader => SimpleResult)(f: => A => Request[T] => Result) =
Security.Authenticated(username, onAuthFailure) { id =>
Action(bodyParser) { request =>
fromSession(id) match {
case Left(err) => {
Logger.error(s"A session value from a request is inconsistent to protocol: $err . Session in header: $id")
onAuthFailure(request).withNewSession
}
case Right(x) => f(x)(request)
}
}
}
}
sealed trait DashboardSecurity extends WebSecurity[User] {
import play.api.mvc.Results.Redirect
override protected def fromSession(param: String): Either[String, User] = Users.getUser(param).map(Right(_)).getOrElse(Left("Invalid Session Id"))
}
def toSession(param: User): (String, String) = (sessionId, param.id.toString)
}
object Dashboard extends Controller with DashboardSecurity {
/**
* Home page of the User
*/
def homePage = GeneralFilter()(loginPage) { id =>
implicit request =>
Ok("Welcome home - " + id)
}
}
在homePage
上方,如果用户未经过身份验证,则会直接将其重定向到loginPage
答案 3 :(得分:0)
我得到了一个解决方案,但不知道它是否是正确的方法。
def generalAccountSetting()=Action{
implicit request=>
try{
val result=User.getResult(session.get("userId").get)// this makes exception, if user not logged in.
if(!result.isEmpty){
Ok(html.general(result(0)))
}
else
Ok(html.onError())
}catch{
case e:Exception=>
println(e.toString)
Redirect("/").withNewSession
}
}//end generalAccountSetting
有更好的方法
def generalAccountSetting() = Action { implicit request =>
try{
session.get("userId").map{user=>
val result=User.getResult(session.get("userId").get)// this makes exception, if user not logged in.
if(!result.isEmpty){
Ok(html.general(result(0)))
}
else
Ok(html.onError())
}.getOrElse{
Redirect("/")
}
}catch{
case e=>
Ok(html.onError())
}
}//end generalAccountSetting