# JWT with Nginx 這次選擇使用[auth0/nginx-jwt](https://github.com/auth0/nginx-jwt)整合 Jwt 認證和 Nginx ,由於這次使用的套件是基於 OpenResty 所實現的,因此先來介紹 OpenResty ## [OpenResty](https://openresty.org/en/) OpenResty是一個基於Nginx的Web平台,可以使用其LuaJIT引擎執行Lua。 ```bash= worker_processes 1; events { worker_connections 1024; } http { server { listen 0.0.0.0:80; location / { default_type text/html; content_by_lua_block { ngx.say("HelloWorld") } } } } ``` ## 相關文件設定 * docker-compose.yml * JWT_SECRET: Jwt secret key * JWT_SECRET_IS_BASE64_ENCODED: Secret key 編碼與否 * LUA_PATH: [auth0/nginx-jwt](https://github.com/auth0/nginx-jwt) script的位置 ```yaml= version: '3' services: web: image: openresty/openresty:centos environment: - JWT_SECRET=ABCD - LUA_PATH=/script/nginx-jwt.lua restart: always volumes: - ./proxy/nginx.conf:/etc/nginx/nginx.conf - ./proxy/conf.d:/etc/nginx/conf.d/ - ./script:/script/ ports: - "8080:80" ``` * /etc/nginx/nginx.conf * lua_package_path: 設定script的位置 ``` events { worker_connections 1024; # multi_accept on; } env JWT_SECRET; http{ lua_package_path "/script/;;"; } ``` * /etc/nginx/conf.d/nginx.conf ``` server { listen 0.0.0.0:80; location /secure { default_type text/html; access_by_lua ' local jwt = require("nginx-jwt") jwt.auth() '; proxy_pass https://www.google.com; } location /notsecure { proxy_pass https://www.google.com; } } ``` ## 問題 * lua 無法讀到環境變數 ```lua= #/script/nginx-jwt.lua local jwt = require "resty.jwt" local cjson = require "cjson" local basexx = require "basexx" local secret = os.getenv("JWT_SECRET") <---無法讀到 ... ``` 但是container中有該環境變數 ``` sh-4.4# printenv HOSTNAME=00b24f897f02 LUA_PATH=/script/nginx-jwt.lua LUA_CPATH=/usr/local/openresty/site/lualib/?.so;/usr/local/openresty/lualib/?.so;./?.so;/usr/local/lib/lua/5.1/?.so;/usr/local/openresty/luajit/lib/lua/5.1/?.so;/usr/local/lib/lua/5.1/loadall.so;/usr/local/openresty/luajit/lib/lua/5.1/?.so PWD=/ HOME=/root JWT_SECRET=SDAWFF TERM=xterm SHLVL=1 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/openresty/luajit/bin:/usr/local/openresty/nginx/sbin:/usr/local/openresty/bin _=/usr/bin/printenv ``` * [https://hub.docker.com/r/openresty/openresty](https://hub.docker.com/r/openresty/openresty) * [https://github.com/openresty/lua-nginx-module#chinese-mailing-list](https://github.com/openresty/lua-nginx-module#chinese-mailing-list) * [https://www.twblogs.net/a/5f0104a099927402d4fcdf31](https://www.twblogs.net/a/5f0104a099927402d4fcdf31) * [http://nginx.org/en/docs/ngx_core_module.html#env](http://nginx.org/en/docs/ngx_core_module.html#env)