title: How can I create a custom directive for Akka-Http 2 by nesting existing Directives?
body: <p>I am trying to create a custom directive that I can later use to validate user roles like so:</p>
  
  <pre><code>val route = put &amp; authorize(ADMIN) { 
                // do sth
              }
  </code></pre>
  
  <p>or </p>
  
  <pre><code>val route = put {
                authorize(ADMIN) {
                  //do sth
                }
              }
  </code></pre>
  
  <p>. Here is what I got so far:</p>
  
  <pre><code>  def authorize(role: String): Directive0 = {
      extractToken { t: String =&gt;
        validateToken(t) {
          extractRoles(t) { roles: Seq[String] =&gt;
            validate(roles.contains(role), s"User does not have the required role")
          }
        }
      }
    }
  
    def extractRoles(token: String): Directive1[Seq[String]] = {
      token match {
        case JsonWebToken(header, claimsSet, signature) =&gt; {
          val decoded = decodeJWT(token)
          decoded match {
            case Some(_) =&gt; provide(extractRoleCodesFromJWT(decoded.get))
            case None =&gt; provide(Seq())
          }
        }
        case x =&gt;
          provide(Seq())
      }
    }
  
    def validateToken(token: String): Directive0 = validate(validateJWT(token), INVALID_TOKEN_MESSAGE)
  
    def extractToken: Directive1[Option[String]] = extractToken | extractHeader
  
    def extractCookie: Directive1[Option[String]] = optionalCookie(JWT_COOKIE_NAME).map(_.map(_.value))
  
    def extractHeader: Directive1[Option[String]] = optionalHeaderValueByName(JWT_HEADER_NAME)
  </code></pre>
  
  <p>All compiles fine, except the actual Directive0 that I want use later (authorize). The most inner line <code>validate(...)</code> shows a compile error saying "Expression of type server.Directive0 doesn't conform to expected type server.Route"</p>
  
  <p>How can I properly nest my other directives in order to form my authorize directive? 
  Or can I concatenate them somehow else, instead of nesting?
  The documentation on custom directives is very slim unfortunately.</p>
  
  <p><strong>[UPDATE]</strong></p>
  
  <p>Thanks to the pointer from Java Anto this is what I came up with.</p>
  
  <pre><code> def authorize(role: String): Directive0 = {
      extractToken.flatMap(validateToken)
                  .flatMap(extractRoles)
                  .flatMap(roles =&gt; validate(roles.contains(role), MISSING_ROLE_MESSAGE))
    }
  </code></pre>
  
  <p>This compiles and will hopefully do the trick one I get to test it properly.</p>