Skip to content

Instantly share code, notes, and snippets.

@teigen
Created July 19, 2012 14:33
Show Gist options
  • Save teigen/3144345 to your computer and use it in GitHub Desktop.
Save teigen/3144345 to your computer and use it in GitHub Desktop.
Unfiltered authentication example
package auth
import unfiltered.Cycle
import unfiltered.request.{HttpRequest, BasicAuth, Path}
import unfiltered.response._
import unfiltered.jetty.Http
import unfiltered.filter.Plan
object Req {
def apply[Req, Res](f:PartialFunction[HttpRequest[Req], HttpRequest[Req] => ResponseFunction[Res]]):Cycle.Intent[Req, Res] = {
case req if f.isDefinedAt(req) => f(req)(req)
}
}
object User {
def apply[Req, Res](f:User => ResponseFunction[Res]):HttpRequest[Req] => ResponseFunction[Res] = {
case BasicAuth(name, _) => f(new User(name))
case _ => Unauthorized ~> WWWAuthenticate("""Basic realm="/"""")
}
}
class User(val name:String)
object Demo extends App with Plan {
def intent = auth orElse noAuth
def auth:Plan.Intent = Req{
case Path("/auth") => User{ user =>
Ok ~> ResponseString(user.name)
}
}
def noAuth:Plan.Intent = {
case Path("/noauth") =>
Ok ~> ResponseString("no user")
}
Http.local(8080).filter(this).run()
}
λ curl -v http://localhost:8080/noauth
* About to connect() to localhost port 8080 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /noauth HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Length: 7
< Server: Jetty(7.6.0.v20120127)
<
* Connection #0 to host localhost left intact
* Closing connection #0
no user~
λ curl -v http://localhost:8080/auth
* About to connect() to localhost port 8080 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /auth HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< WWW-Authenticate: Basic realm="/"
< Content-Length: 0
< Server: Jetty(7.6.0.v20120127)
<
* Connection #0 to host localhost left intact
* Closing connection #0
~
λ curl -v -u foo:bar http://localhost:8080/auth
* About to connect() to localhost port 8080 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
* Server auth using Basic with user 'foo'
> GET /auth HTTP/1.1
> Authorization: Basic Zm9vOmJhcg==
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Length: 3
< Server: Jetty(7.6.0.v20120127)
<
* Connection #0 to host localhost left intact
* Closing connection #0
foo~
λ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment