2

Spray is hard!! I now know that my knowledge on HTTP protocol is not nearly enough and API design isn't easy. However, I still very much want my practice app to work. I'm writing this authentication for POST/PUT/DELETE method. It appears that there are at least two ways to do this: BasicAuth or write a custom directive.

I found this article:

BasicAuth: https://github.com/jacobus/s4/blob/master/src/main/scala/s4/rest/S4Service.scala

I'm trying it out because it looks simple.

The compile and run stages are fine, and the server runs. However, when I'm trying to send a PUT request to test the implementation (using Python's Httpie: http PUT 127.0.0.1:8080/sec-company/casper username=username token=123), the feedback is:HTTP/1.1 404 Not Found

Here's my route:

pathPrefix("sec-company") {
        path("casper") {
          //first examine username and token
          authenticate(BasicAuth(CustomUserPassAuthenticator, "company-security")) {userProfile =>
            post { ctx =>
              entity(as[Company.Company]) { company =>
                complete {
                  company
                }
              }
            }
   }

Here is my implementation of UserPassAuthenticator:

object CustomUserPassAuthenticator extends UserPassAuthenticator[UserProfile] {
    def apply(userPass: Option[UserPass]) = Promise.successful(
      userPass match {
        case Some(UserPass(user, token)) => getUserProfile(user, token)
        case _ => None
      }
    ).future
  }

First of all, is this the right way to implement authentication? Second, where does UserPassAuthenticator find the username and password?? Can I send back a better HTTP header other than 404 to indicate failed authentication?

If this is far from correct, is there any tutorial on authentication that I can follow? TypeSafe's Spray templates are more about overall patterns and less about Spray's functionality!

Thank you!

1 Answer 1

5

I had the same problem, even after looking at https://github.com/spray/spray/wiki/Authentication-Authorization (which says it's for an older version of Akka but it still seems to apply) I came up with the following:

trait Authenticator {
  def basicUserAuthenticator(implicit ec: ExecutionContext): AuthMagnet[AuthInfo] = {
    def validateUser(userPass: Option[UserPass]): Option[AuthInfo] = {
      for {
        p <- userPass
        user <- Repository.apiUsers(p.user)
        if user.passwordMatches(p.pass)
      } yield AuthInfo(user)
    }

    def authenticator(userPass: Option[UserPass]): Future[Option[AuthInfo]] = Future { validateUser(userPass) }

    BasicAuth(authenticator _, realm = "Private API")
  }
}

I mix in this trait into the Actor that runs the routes and then I call it like this:

runRoute(
  pathPrefix("api") {
    authenticate(basicUserAuthenticator) { authInfo =>
      path("private") {
        get {
          authorize(authInfo.hasPermission("get") {
            // ... and so on and so forth
          }
        }
      }
    }
  }
}

The AuthInfo object returned by the validateUser method is passed as a parameter to the closure given to the authorize method. Here it is:

case class AuthInfo(user: ApiUser) {
  def hasPermission(permission: String) = user.hasPermission(permission)
}

In Spray (and HTTP), authentication (determining whether you have a valid user) is separate from authorization (determining whether the user has access to a resource). In the ApiUser class I also store the set of permissions the user has. This is a simplified version, my hasPermission method is a bit more complex since I also parametrize permissions, so it's not just that a particular user has permission to do a get on a resource, he might have permission to read only some parts of that resource. You might make things very simple (any logged-in user can access any resource) or extremely complex, depending on your needs.

As to your question, when using HTTP BASIC authentication (the BasicAuth object), the credentials are passed in the request in an Authorization: header. Your HTTP library should take care of generating that for you. According to the HTTP standard, the server should return a 401 status code if the authentication was incorrect or not provided, or a 403 status code if the authentication was correct but the user doesn't have permissions to view the content.

5
  • Repository.apiUsers(login: String) is how I get my User object from my database given their login. In your case you would need to go to the DB or wherever you're storing your users' credentials and get it from there. user.passwordMatches is a method in my User class that verifies whether the given password matches the user's password (since it's stored hashed and salted). I hope that's clear! Jul 1, 2014 at 13:52
  • Thank you so much! That's much clearer. But what should AuthInfo look like? How can I also give user the opportunity to send username&password (or just an authentication token) from POST body or GET query?
    – windweller
    Jul 1, 2014 at 15:55
  • I missed that... I've edited the answer to add info about AuthInfo. Now that I look at it, I should really turn this into a blog post :) Jul 2, 2014 at 13:52
  • You should and post the link here! I'll read it! This is a really important topic. Btw, I tried this solution, but this way, if authen failed, Spray doesn't return 401 response, and you have to do it by yourself using complete(401, "failed")
    – windweller
    Jul 2, 2014 at 16:12
  • Here's the post. Enjoy :) mcamou.github.io/blog/2014/07/07/… Jul 7, 2014 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.