控制器中的授权检查-Scala/Play [英] Authorisation check in controller - Scala/Play

查看:98
本文介绍了控制器中的授权检查-Scala/Play的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Play Framework中控制器的简单示例,其中每个操作都会检查会话-如果用户已登录.

This is a simple example of a controller in Play Framework where every action checks the session - if the user is logged in.

object Application extends Controller {

    def index = Action { implicit request =>
        if (request.session.isEmpty) {
            Redirect("/login")
        } else {
            Ok(views.html.index("index"))
        }
    }

    def about = Action { implicit request =>
        if (request.session.isEmpty) {
            Redirect("/login")
        } else {
            Ok(views.html.index("about"))
        }
    }

}

我想在构造函数中处理会话检查,而不是在每个操作方法中进行,但我只是不知道怎么办?它应该看起来像这样:

I'd like to handle the session checking in the constructor instead of every action method, but I just don't know how? It should look something like this:

object Application extends Controller {

    //This is where the constructor would check if session exists
    //and if not - redirect to login screen

    def index = Action {
        Ok(views.html.index("index"))
    }

    def about = Action {
        Ok(views.html.index("about"))
    }

}

这可能吗?如果可以,怎么办?

Is this possible and if so then how?

我的堆栈是Play Framework 2.2.1,Scala 2.10.3,Java 1.8.0-ea 64位

My stack is Play Framework 2.2.1, Scala 2.10.3, Java 1.8.0-ea 64bit

更新-已解决:感谢您的所有想法,现在已找到解决方案,请参阅我的答案.

UPDATE - SOLVED Thanks for all your ideas, solution is now found, see my answer.

推荐答案

解决方案是使用操作组合并创建自定义操作.

Solution is to use Action Composition and create a custom action.

Auth.scala:

Auth.scala:

package core

import play.api.mvc._
import scala.concurrent._
import play.api.mvc.Results._

object AuthAction extends ActionBuilder[Request] {

    def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[SimpleResult]) = {
        if (request.session.isEmpty) {
            //authentication condition not met - redirect to login page
            Future.successful(Redirect("/login"))
        } else {
            //proceed with action as normal
            block(request)
        }
    }

}

Application.scala:

Application.scala:

package controllers

import play.api._
import play.api.mvc._
import core._

object Application extends Controller {

    def index = AuthAction {
        Ok(views.html.index("You are logged in."))
    }

}

这篇关于控制器中的授权检查-Scala/Play的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆