authorize

Signature

def authorize(check: ⇒ Boolean): Directive0
def authorize(check: RequestContext ⇒ Boolean): Directive0

Description

Applies the given authorization check to the request.

The user-defined authorization check can either be supplied as a => Boolean value which is calculated just from information out of the lexical scope, or as a function RequestContext => Boolean which can also take information from the request itself into account.

If the check returns true the request is passed on to the inner route unchanged, otherwise an AuthorizationFailedRejection is created, triggering a 403 Forbidden response by default (the same as in the case of an AuthenticationFailedRejection).

In a common use-case you would check if a user (e.g. supplied by any of the authenticate* family of directives, e.g. authenticateBasic) is allowed to access the inner routes, e.g. by checking if the user has the needed permissions.

See also authorizeAsync for the asynchronous version of this directive.

Note

See also Authentication vs. Authorization to understand the differences between those.

Example

case class User(name: String)

// authenticate the user:
def myUserPassAuthenticator(credentials: Credentials): Option[User] =
  credentials match {
    case Credentials.Provided(id) => Some(User(id))
    case _                        => None
  }

// check if user is authorized to perform admin actions:
val admins = Set("Peter")
def hasAdminPermissions(user: User): Boolean =
  admins.contains(user.name)

val route =
  Route.seal {
    authenticateBasic(realm = "secure site", myUserPassAuthenticator) { user =>
      path("peters-lair") {
        authorize(hasAdminPermissions(user)) {
          complete(s"'${user.name}' visited Peter's lair")
        }
      }
    }
  }

// tests:
val johnsCred = BasicHttpCredentials("John", "p4ssw0rd")
Get("/peters-lair") ~> addCredentials(johnsCred) ~> // adds Authorization header
  route ~> check {
    status shouldEqual StatusCodes.Forbidden
    responseAs[String] shouldEqual "The supplied authentication is not authorized to access this resource"
  }

val petersCred = BasicHttpCredentials("Peter", "pan")
Get("/peters-lair") ~> addCredentials(petersCred) ~> // adds Authorization header
  route ~> check {
    responseAs[String] shouldEqual "'Peter' visited Peter's lair"
  }
The source code for this page can be found here.