Skip to content

Instantly share code, notes, and snippets.

@tk3
Last active December 10, 2015 07:30
Show Gist options
  • Save tk3/a9663d9b82e3965f36f8 to your computer and use it in GitHub Desktop.
Save tk3/a9663d9b82e3965f36f8 to your computer and use it in GitHub Desktop.
ngx_mruby: basic authentication
def basic_auth
r = Nginx::Request.new
realm_name = r.var.realm_name
if r.headers_in["Authorization"].nil?
r.headers_out["WWW-Authenticate"] = %Q(Basic realm="#{realm_name}")
return Nginx::HTTP_UNAUTHORIZED
end
auth = r.headers_in["Authorization"]
params = Base64::decode(auth.split(" ")[1]).split(":")
unless yield(params[0], params[1])
r.headers_out["WWW-Authenticate"] = %Q(Basic realm="#{realm_name}")
return Nginx::HTTP_UNAUTHORIZED
end
return Nginx::DECLINED
end
def load_user_list(file)
users = {}
IO.open(IO.sysopen((file))) {|io|
io.each {|line|
params = line.chomp.split("\t")
users[params[0]] = params[1] if 1 < params.size
}
}
users
end
r = Nginx::Request.new
users = load_user_list(r.var.user_list)
Nginx.return basic_auth {|id, password|
users.key?(id) && users[id] == password
}
#!/bin/sh
[ -f ./nginx-1.6.2.tar.gz ] || curl -O http://nginx.org/download/nginx-1.6.2.tar.gz
[ -d ./ngx_mruby ] || git clone https://github.com/matsumoto-r/ngx_mruby.git
tar zxf nginx-1.6.2.tar.gz
_nginx_src=`pwd`/nginx-1.6.2
_nginx_mruby_src=`pwd`/ngx_mruby
cd ngx_mruby
ruby -pe '$_.gsub!(/^end/, " conf.gem :github => \"mattn/mruby-base64\"\nend")' -i build_config.rb
git submodule init
git submodule update
NGINX_CONFIG_OPT_ENV='--prefix=/usr/local/nginx' NGINX_SRC_ENV=$_nginx_src sh build.sh
sudo make install
worker_processes 1;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
set $realm_name 'Private Page';
set $user_list '/usr/local/nginx/conf/user.list';
mruby_access_handler '/usr/local/nginx/mruby/basic_auth.rb';
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
user01 pass01
user02 pass02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment