Skip to content

Instantly share code, notes, and snippets.

@jaytaph
Created July 6, 2012 19:41
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jaytaph/3062338 to your computer and use it in GitHub Desktop.
Save jaytaph/3062338 to your computer and use it in GitHub Desktop.
Varnish oauth offloader
<?php
// Crude check. Off course this should be stored in a (memory) database. $token is an
// access token that is provided by oauth.
$token = $_SERVER['HTTP_X_AUTH_TOKEN'];
if ($token == "mellon") {
header("X-Api-User: Gandalf");
header("X-Api-Context: Middle-Earth");
header("Cache-Control: public, max-age=120");
} elseif ($token == "kensentme") {
header("X-Api-User: Larry");
header("X-Api-Context: Sierra");
header("Cache-Control: public, max-age=60");
} else {
// Don't know this token. Access denied!
header("HTTP/1.1 401 Access Denied");
}
backend default {
.host = "api.example.org";
.port = "80";
}
backend oauth {
.host = "oauth.example.internal";
.port = "80";
}
sub vcl_recv {
if (req.restarts == 1) {
set req.backend = default;
set req.http.host = "api.example.org";
return(lookup);
}
unset req.http.x-api-user;
unset req.http.x-api-context;
unset req.http.x-restart;
if (req.url ~ "^/oauth/") {
set req.backend = oauth;
set req.http.host = "oauth.example.internal";
set req.url = regsub(req.url, "^/oauth/", "/");
return(pipe);
}
if (req.http.x-auth-token) {
set req.backend = oauth;
set req.http.host = "oauth.example.internal";
return(lookup);
}
error 401 "Not Authorized";
}
sub vcl_miss {
if (req.http.x-auth-token && req.backend == oauth) {
set bereq.url = "/checktoken.php";
set bereq.request = "HEAD";
}
}
sub vcl_hit {
if (req.http.x-auth-token && req.backend == oauth) {
set req.http.x-api-user = obj.http.x-api-user;
set req.http.x-api-context = obj.http.x-api-context;
set req.http.x-restart = "1";
}
}
sub vcl_fetch {
if (req.http.x-auth-token && req.backend == oauth) {
if (beresp.status != 200) {
error 401 "Not Authorized";
}
set req.http.x-api-user = beresp.http.x-api-user;
set req.http.x-api-context = beresp.http.x-api-context;
set req.http.x-restart = "1";
return(deliver);
}
}
sub vcl_deliver {
if (req.http.x-restart) {
unset req.http.x-restart;
return(restart);
}
}
sub vcl_hash {
if (req.http.x-auth-token && req.backend == oauth) {
hash_data("TOKEN " + req.http.x-auth-token);
return(hash);
}
if (req.http.x-api-user) {
hash_data(req.http.x-api-user);
hash_data(req.http.x-api-context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment