简体   繁体   中英

How to secure APIs in Scala

Use the following class while implementing in Java @Security.Authenticated(Secured.class) and getUsername , onUnauthorized methods in Secured.java File. But how to do that same thing in Scala?

I've done it in a Play Framework project using Secured trait:

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 above is an authentication controller:

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"
    )
  }
}

Then an example of a secured page controller:

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 is case class that simply loads the data from DB using anorm. Finally, the related part of routes :

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

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

There are two html templates referenced above: login.scala.html and mypage.scala.html but I'm not showing them here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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