建一个自己用的网站要多少钱seo怎么收费seo
#在CentOS7环境中,实现使用openresty配置文件,达到jwt指定用户userid不能访问的效果。
首先,你需要安装 OpenResty 和 JWT 组件:
- 安装 OpenResty
参考 OpenResty 的官方安装文档,在终端执行如下命令:
$ sudo yum install yum-utils
$ sudo yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
$ sudo yum install openresty
- 安装 LuaRocks 和 JWT
$ sudo yum install epel-release -y
$ sudo yum install lua-nginx* -y
$ sudo yum install curl -y
$ sudo yum install wget -y
$ sudo yum localinstall https://luarocks.org/releases/luarocks-3.5.0.tar.gz
$ sudo luarocks install lua-resty-jwt
接下来,你可以在 OpenResty 配置文件中实现需求:
- 在 nginx.conf 文件中,添加
http
块:
http {
...
}
- 在
http
块中添加以下内容:
# 在 server 块中定义变量
lua_shared_dict jwt_dict 10m;
init_by_lua_block {local jwt = require "resty.jwt"local jwt_secret = "your-jwt-secret"-- 将 jwt 验证结果保存到共享内存中function save_jwt_result(jwt_result)local dict = ngx.shared.jwt_dictlocal key = ngx.var.http_authorizationlocal expires = 60 * 60 -- 设置过期时间为一小时if jwt_result.valid thendict:set(key, jwt_result.payload, expires)elsedict:set(key, 0, expires)endend-- 验证 jwtfunction validate_jwt()local auth_header = ngx.var.http_authorizationif not auth_header thenngx.exit(401)endlocal jwt_token = string.match(auth_header, "^Bearer%s+(.+)$")if not jwt_token thenngx.exit(401)endlocal jwt_obj = jwt:verify(jwt_secret, jwt_token)save_jwt_result(jwt_obj)if not jwt_obj.valid thenngx.exit(401)endend
}# 定义 server 块
server {listen 7000;server_name localhost;# 声明 location 块,匹配 /api/ 开头的请求location ^~ /api/ {# 验证 jwtaccess_by_lua_block {validate_jwt()-- 查询 PostgreSQL 数据库,获取 accountblack 表-- 如果用户 userid 被加入了黑名单,返回 403 状态码,否则继续执行local pgsql = require("resty.postgres")local pg = pgsql:new()pg:set_timeout(1000)-- 连接 PostgreSQL 数据库local ok, err = pg:connect{host = "your-postgres-db-host",port = 5432,database = "your-postgres-db-name",user = "your-postgres-db-username",password = "your-postgres-db-password"}if not ok thenngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)end-- 查询用户是否在黑名单中local account_black_sql = string.format("SELECT accountid FROM accountblack WHERE userid = %s", ngx.var.jwt_payload.sub)local account_black_result, err = pg:query(account_black_sql)if not account_black_result thenngx.log(ngx.ERR, "Failed to query accountblack: ", err)ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)endif account_black_result[1] ~= nil thenngx_exit(ngx.HTTP_FORBIDDEN)end}# 转发请求proxy_pass http://172.16.01.6:8029/;}
}
- 其中,
save_jwt_result(jwt_result)
函数用于将 jwt 验证结果存储到共享内存中,validate_jwt()
函数用于验证 jwt,access_by_lua_block
即 access 阶段执行的 Lua 代码块。在access_by_lua_block
中,我们查询 PostgreSQL 数据库,获取accountblack
表,如果用户 userid 在黑名单中,返回 403 状态码,否则继续执行,并将请求转发到http://172.16.01.6:8029/
。
当用户请求 /api/
接口时,将会首先执行 validate_jwt()
函数,验证 jwt 是否有效。如果 jwt 有效,我们将会查询 PostgreSQL 数据库,检查用户 userid 是否在黑名单表中。如果用户在黑名单中,请求将会被拒绝并返回 403 状态码;否则请求将会被转发到指定地址,并且在转发过程中会自动添加上验证后的 jwt 信息。