Nginx+Lua实现图片链接Token鉴权方案
近期在使用Minio文件服务器处理图片上传与展示业务时,发现其提供的临时访问链接鉴权能力较弱,无法实现严格的权限控制,且直接暴露原始IP地址也存在安全隐患。
为解决上述问题,计划采用Nginx作为反向代理以隐藏后端真实IP。在实施过程中,参考网络资料利用Lua脚本实现鉴权逻辑,经过多次调试与验证,最终成功部署,现将具体实现过程记录如下。
本方案使用的核心工具为OpenResty,它是集成了Lua模块的Nginx发行版,配置相对简便。
需下载lua-resty-http第三方库,解压后将对应的.lua文件放置于lualib\resty目录下即可使用。
整体流程为:用户发起请求到达Nginx,根据图片路径策略匹配规则,随后执行Lua代码向后端发送HTTP请求进行Token鉴权;若校验通过,则代理转发至具体的图片服务器;若失败,则返回无权限提示。
以下是Nginx配置文件中的关键代码片段。
http {
# 定义全局变量
init_by_lua_block {
cjson = require "cjson";
http = require "resty.http";
}
server {
location ~^/(api)/image/(.*)$ {
rewrite_by_lua_block {
-- local cjson = require "cjson"
-- local http = require "resty.http"
local httpc = http.new()
local ngx = ngx
local headers = ngx.req.get_headers()
-- get请求参数中T就是token
local token = headers["token"]
local request_method = ngx.var.request_method
local args = nil
if "GET" == request_method then
args = ngx.req.get_uri_args()
elseif "POST" == request_method then
ngx.req.read_body()
args = ngx.req.get_post_args()
end
token = args["token"];
if not token then
ngx.header['Content-Type'] = 'text/plain; charset=utf-8';
ngx.status = ngx.HTTP_FORBIDDEN
ngx.say("您无权限浏览该图片。")
ngx.exit(200)
end
-- 字符串拼接
-- 你要实现token鉴权的服务,header和参数都给你实现了,根据实际需要选择
local url = "http://127.0.0.1:8080/image/checkToken?token="..token;
local res, err = httpc:request_uri(url, {method="GET", headers={["token"]=token}})
if not res then
ngx.header['Content-Type'] = 'text/plain; charset=utf-8';
ngx.say(cjson.encode({message = "Error getting response",status = ngx.HTTP_INTERNAL_SERVER_ERROR }));
ngx.exit(200)
end
if res.body == '0' then
ngx.header['Content-Type'] = 'text/plain; charset=utf-8';
ngx.say("您无权限浏览该图片。");
ngx.exit(200)
end
}
proxy_pass http://yourip:9000/$2;
}
}
}
Java后端用于接收并校验Token的代码示例。
@RestController
@RequestMapping("/image")
public class TokenResource {
@RequestMapping("/checkToken")
public String checkToken(HttpServletRequest request, String token) {
System.out.println("程序进来了");
String header = request.getHeader("token");
System.out.println("头部token:" + header);
if (StringUtils.isEmpty(token)) {
System.out.println(token + ":0");
return "0";
}
if ("1".equals(token)) {
System.out.println(token + ":1");
return "1";
}
return "0";
}
}
当Token校验通过时,Nginx不会拦截请求,Lua代码执行完毕后,请求将继续沿Nginx配置的转发路径流向后端服务。
proxy_pass http://your_ip:9000/$2
注意正则表达式写法,若将location规则写成~^/api/image/(.*)$,则proxy_pass指令应调整为http://your_ip:9000/$1。
至此,关于使用Nginx结合Lua进行Token鉴权的完整方法介绍完毕,更多相关内容可参考本站过往文章或继续浏览后续推荐内容。