使用Nginx和Lua進(jìn)行JWT校驗(yàn)介紹
因?yàn)椴簧婕暗綌?shù)據(jù)庫(kù)和其它資源的依賴,jwt本身也是無(wú)狀態(tài)的。因此鑒權(quán)服務(wù)沒有再基于Java或者其它語(yǔ)言來(lái)做。而是使用lua腳本對(duì)nginx做了一個(gè)增強(qiáng):使用lua腳本來(lái)校驗(yàn)token是否有效,無(wú)效直接返回401,有效則原樣轉(zhuǎn)發(fā)。
Lua腳本
這里的secret我遇到了很大的坑。一開始直接從Java后端項(xiàng)目中復(fù)制了密鑰出來(lái),但是一直提示signature mismatch:
,后來(lái)發(fā)現(xiàn)后端應(yīng)用中使用base64decode相關(guān)方法,在Lua腳本中增加了ngx.decode_base64(secret)
處理secret后解決問題。其實(shí)到這里還沒有解決問題,在后端debug代碼的時(shí)候,發(fā)現(xiàn)后端密鑰被decode的結(jié)果是一串亂碼,為了避免亂碼的問題,通過https://www.base64encode.org/重新生成secret才最終解決了問題。
如果你的項(xiàng)目中也遇到了這個(gè)signature mismatch:
錯(cuò)誤,需要排查一下后端在生成token的時(shí)候,是否有對(duì)secret進(jìn)行decode或者其它處理,在lua腳本中也要進(jìn)行相應(yīng)的處理。
nignx.conf配置
-- nginx-jwt.lua local cjson = require "cjson" local jwt = require "resty.jwt" --your secret local secret = "yoursecrethere" --無(wú)需鑒權(quán)api清單 local no_need_token_api_list = {'/api/register', '/api/login'} local function ignore_url (val) for index, value in ipairs(no_need_token_api_list) do if (value == val) then return true end end return false end local M = {} function M.auth() if ignore_url(ngx.var.request_uri) then return else end -- require Authorization request header local auth_header = ngx.var.http_Authorization if auth_header == nil then ngx.log(ngx.WARN, "No Authorization header") ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- require Bearer token local _, _, token = string.find(auth_header, "Bearer%s+(.+)") if token == nil then ngx.log(ngx.ERR, "Missing token") ngx.exit(ngx.HTTP_UNAUTHORIZED) end --decode_base64和后端保持一致 local jwt_obj = jwt:verify(ngx.decode_base64(secret), token) if jwt_obj.verified == false then ngx.log(ngx.ERR, "Invalid token: ".. jwt_obj.reason) ngx.status = ngx.HTTP_UNAUTHORIZED ngx.say(cjson.encode(jwt_obj)) ngx.header.content_type = "application/json; charset=utf-8" ngx.exit(ngx.HTTP_UNAUTHORIZED) end end return M
Dockerfile配置
worker_processes 1; events { worker_connections 1024; } http { lua_package_path "/opt/lua-resty-jwt/lib/?.lua;;"; upstream backend { server 192.168.1.1:8080; } access_log /logs/nginx_access.log; error_log /logs/nginx_error.log; server { listen 80; #后端api接口代理 location /api/ { access_by_lua_block { local obj = require('nginx-jwt') obj.auth() } proxy_pass http://backend; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } }
到此這篇關(guān)于使用Nginx和Lua進(jìn)行JWT校驗(yàn)介紹的文章就介紹到這了,更多相關(guān)Nginx和Lua進(jìn)行JWT校驗(yàn)內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。