繁体   English   中英

如何在Scala中保护API

[英]How to secure APIs in Scala

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

我已经在Play框架项目中使用Secured特性完成了此任务:

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()

login.scala.html两个html模板: login.scala.htmlmypage.scala.html但我不在这里显示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM