openresty配置资源访问控制

openresty配置资源访问控制

介绍

我们这的需求是,arcgis server发布了很多图层数据,这些数据需要被用户申请后才能访问。申请后给用户一个地址和key,让用户可以用key和地址访问地图资源。

这里我准备使用openresty和认证服务(java)来实现。

实现思路如下所示:

openresty资源访问控制

openresty准备

为了实现相关的思路和逻辑,我们需要编写lua脚本,并且可以访问http请求接口。

这里我们使用GitHub上的resty组件,lua-resty-http

image-20221227170354420

image-20221227170436894

我需要解压后的三个lua脚本文件即可

image-20221227170518004

解压后将.lua文件放到 lualib\resty目录下就行

image-20221227170623255

这里openresty就已经支持lua请求http了

编写lua脚本

这里编辑nginx文件下conf目录的nginx.conf

  # 定义全局变量
    init_by_lua_block {
    
    
		cjson = require "cjson";
		http = require "resty.http";
	}

server {
    
    
        listen       80;
        server_name  localhost;
       
	location / {
    
    
		rewrite_by_lua_block {
    
    
			local httpc = http.new()
			local ngx = ngx
			local headers = ngx.req.get_headers()
			# get请求参数中authKey就是key
			local authKey = headers["authKey"]
			local request_method = ngx.var.request_method
			local args = nil
			local uri = ngx.var.uri
			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
				
			authKey = args["authKey"];
			if not authKey then
				ngx.header['Content-Type'] = 'text/plain; charset=utf-8';
				ngx.status = ngx.HTTP_UNAUTHORIZED
				ngx.say("没有token")
				ngx.exit(200)
			end
			# 字符串拼接
			# 你要实现key鉴权的服务,这里是参数请求,根据实际需要选择
			local url = "http://127.0.0.1:8068/resource/center/check-server?authKey="..authKey.."&mapServer="..uri;
				
			local res, err = httpc:request_uri(url, {
    
    method="GET", headers={
    
    ["authKey"]=authKey}})
				
			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://localhost:6080/;
		}

    }

解释一下:

这里我用80端口代理本地arcgis server 6080端口,首先我会拦截请求地址里面的authKey如果没有key直接拒绝请求返回401,如果有key则将key和请求地图服务的地址一起发送到java后台进行鉴权,后台通过了则可以继续访问,后台拒绝则返回403。具体的鉴权逻辑,根据实际情况来实现就行。这里后台通过就返回1给openresty,不通过返回0。

java接口示例

    @GetMapping(value = "check-server")
    @ApiOperation(value = "验证是否可以访问地图资源")
    public Integer checkServer(@RequestParam("authKey") String authKey,@RequestParam("mapServer") String mapServer){
    
    
        //在service层实现具体逻辑
        return resourceMapService.checkServer(authKey,mapServer);
    }

猜你喜欢

转载自blog.csdn.net/qq_36213352/article/details/128465819