日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

使用Nginx和Lua進行JWT校驗介紹_nginx

作者:jiangshanwe ? 更新時間: 2022-02-24 編程語言

前言

因為不涉及到數據庫和其它資源的依賴,jwt本身也是無狀態的。因此鑒權服務沒有再基于Java或者其它語言來做。而是使用lua腳本對nginx做了一個增強:使用lua腳本來校驗token是否有效,無效直接返回401,有效則原樣轉發。

Lua腳本

這里的secret我遇到了很大的坑。一開始直接從Java后端項目中復制了密鑰出來,但是一直提示signature mismatch:,后來發現后端應用中使用base64decode相關方法,在Lua腳本中增加了ngx.decode_base64(secret)處理secret后解決問題。其實到這里還沒有解決問題,在后端debug代碼的時候,發現后端密鑰被decode的結果是一串亂碼,為了避免亂碼的問題,通過https://www.base64encode.org/重新生成secret才最終解決了問題。
如果你的項目中也遇到了這個signature mismatch:錯誤,需要排查一下后端在生成token的時候,是否有對secret進行decode或者其它處理,在lua腳本中也要進行相應的處理。

在這里插入圖片描述

nignx.conf配置

-- nginx-jwt.lua


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

--your secret
local secret = "yoursecrethere"
--無需鑒權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;
    }
  }

}

原文鏈接:https://blog.csdn.net/jiangshanwe/article/details/121956714

欄目分類
最近更新