OpenResty 入门实战(2)--简单使用

发布时间 2023-07-30 21:25:04作者: 且行且码

本文主要介绍 OpenResty 结合 lua 的使用,Nginx 功能的一般使用可参考:Nginx 入门实战(2)--简单使用;文中所使用到的软件版本:Centos 7.9.2009、OpenResty 1.21.4.2。

1、hello world

server {
  listen 9096;
  server_name  localhost-9096;
  access_log  logs/access-9096.log;

  location /hello {
    default_type text/html;
    content_by_lua_block {
      ngx.say("<p>hello, world</p>")
    }
  }
}

访问相应的地址:

2、jwt token 验证

可以使用 OpenResty 来验证带有 jwt token 的请求,如果验证不通过返回 401 状态码。

2.1、安装 jwt 的 lua 插件

2.1.1、下载插件

下载 lua-resty-jwt 和 lua-resty-hmac 插件:
lua-resty-jwt: https://github.com/SkyLothar/lua-resty-jwt
lua-resty-hmac: https://github.com/jkeys089/lua-resty-hmac

下载后解压:

tar zxvf lua-resty-jwt-0.1.11.tar.gz
unzip lua-resty-hmac-0.06-1.zip

2.1.2、拷贝插件

在 OpenResty 安装目录下新建 lualib-extend 目录,并拷贝两个插件的 lib/resty 目录到该目录下:

/home/mongo/soft/openresty-1.21.4.2 为  OpenResty 的安装目录。

2.1.3、配置 lua 目录

在 nginx/conf/nginx.conf 配置文件中 http 元素下配置 lua 目录:

http {
    ...
    
    lua_package_path '/home/mongo/soft/openresty-1.21.4.2/lualib-extend/?.lua;;';
    
    ...

2.2、编写验证 token 的 lua 程序

新建 nginx/conf/token.lua 文件:

local cjson = require "cjson"
local jwt = require "resty.jwt"

local redirect = "false";
local status = "";

local token = ngx.req.get_headers()["X-AUTH-TOKEN"];

if token == nil then
    redirect = "true";
    status = "NO_TOKEN";
else
    local jwt_obj = jwt:verify("12345678123456781234567812345678",token);
    if not jwt_obj["verified"] then
        redirect = "true";
        status = "INVALID_TOKEN";
    end
end

if redirect == "true" then
    ngx.status = ngx.HTTP_UNAUTHORIZED;
    ngx.header.content_type = "application/json; charset=utf-8";
    ngx.say(status);
    return ngx.exit(ngx.HTTP_UNAUTHORIZED);
end

2.3、通过 token.lua 验证请求

server {
  listen 9096;
  server_name  localhost-9096;
  access_log  logs/access-9096.log;

  location /hello {
    default_type text/html;
    content_by_lua_block {
      ngx.say("<p>hello, world</p>")
    }
  }

  location /token {
    access_by_lua_file conf/token.lua;
    proxy_pass http://10.49.196.33:9096/hello;
  }
}

A、不带 token 访问时

B、使用错误 token 访问时

C、使用正确 token 访问时