Guards access to the inner route with a user-defined check.


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


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 the authenticate directive) is allowed to access the inner routes, e.g. by checking if the user has the needed permissions.


def extractUser(userPass: UserPass): String = userPass.user
val config = ConfigFactory.parseString("John = p4ssw0rd\nPeter = pan")
def hasPermissionToPetersLair(userName: String) = userName == "Peter"

val route =
  sealRoute {
    authenticate(BasicAuth(realm = "secure site", config = config, createUser = extractUser _)) { userName =>
      path("peters-lair") {
        authorize(hasPermissionToPetersLair(userName)) {
          complete(s"'$userName' visited Peter's lair")

val johnsCred = BasicHttpCredentials("John", "p4ssw0rd")
Get("/peters-lair") ~>
  addCredentials(johnsCred) ~>  // adds Authorization header
  route ~> check {
    status === StatusCodes.Forbidden
    responseAs[String] === "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] === "'Peter' visited Peter's lair"