如何在Scala中保护API

时间:2014-11-07 12:09:57

标签: scala

在Java @Security.Authenticated(Secured.class)中实现时使用以下类 getUsername文件中的onUnauthorizedSecured.java方法。 但是如何在Scala中做同样的事情?

1 个答案:

答案 0 :(得分:1)

我使用Secured trait:

在Play Framework项目中完成了它
package controllers

import play.api.mvc._

trait Secured {

  /**
   * Retrieve the connected user login.
   */
  private def username(request: RequestHeader) = request.session.get("login")

  /**
   * Redirect to login if the user in not authorized.
   */
  private def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login)

  /**
   * Action for authenticated users.
   */
  def IsAuthenticated(f: => String => Request[AnyContent] => Result) = Security.Authenticated(username, onUnauthorized) {
    user =>
      Action(request => f(user)(request))
  }
}
上面的

Application是身份验证控制器:

package controllers

import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models._
import views._

object Application extends Controller {

  val loginForm = Form(
    tuple(
      "login" -> text,
      "password" -> text
    ) verifying("Invalid user or password", result => result match {
      case (login, password) => User.authenticate(login, password).isDefined
    })
  )

  /**
   * Login page.
   */
  def login = Action { implicit request =>
    Ok(html.login(loginForm))
  }

  /**
   * Handle login form submission.
   */
  def authenticate = Action { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.login(formWithErrors)),
      user => Redirect(routes.Home.index()).withSession("login" -> user._1)
    )
  }

  /**
   * Logout and clean the session.
   */
  def logout = Action {
    Redirect(routes.Home.index()).withNewSession.flashing(
      "success" -> "You've been logged out"
    )
  }
}

然后是安全页面控制器的一个例子:

package controllers

import play.api.mvc._
import models._
import views._
import play.api.Logger

object MyPage extends Controller with Secured {

  def index() = IsAuthenticated { username => implicit request =>
    Ok(
      html.mypage(
        User.findByUsername(username)
      )
    )
  }
}

User是一个案例类,只使用anorm从DB加载数据。最后,routes的相关部分:

# Authentication
GET         /login                            controllers.Application.login()
POST        /login                            controllers.Application.authenticate()
GET         /logout                           controllers.Application.logout()

# MyPage
GET         /mypage                           controllers.MyPage.index()

上面引用了两个html模板:login.scala.htmlmypage.scala.html,但我没有在这里显示它们。