Introduction to JWT Verification Using Nginx and Lua

Introduction to JWT Verification Using Nginx and Lua

Preface

Because it does not involve dependencies on databases and other resources, jwt itself is also stateless. Therefore, the authentication service is no longer based on Java or other languages. Instead, we use the Lua script to enhance nginx: we use the Lua script to verify whether the token is valid. If it is invalid, we return 401 directly. If it is valid, we forward it as is.

Lua Script

I encountered a big pit with the secret here. At first, I copied the key directly from the Java backend project, but it kept prompting signature mismatch: Later, I found that the backend application used base64decode related methods. I added ngx.decode_base64(secret) to the Lua script to process the secret and solved the problem. In fact, the problem has not been solved yet. When debugging the backend code, it was found that the result of the backend key being decoded was a string of garbled characters. In order to avoid the problem of garbled characters, the secret was regenerated through https://www.base64encode.org/, which finally solved the problem.
If you also encounter this signature mismatch: error in your project, you need to check whether the backend decodes or otherwise processes the secret when generating the token, and perform corresponding processing in the Lua script.

insert image description here

nignx.conf configuration

--nginx-jwt.lua


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

--your secret
local secret = "yoursecrethere"
--No authentication required API list 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 is consistent with the backend 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 configuration

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;

    #Backend api interface proxy 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;
    }
  }

}

This is the end of this article about using Nginx and Lua for JWT verification. For more information about Nginx and Lua for JWT verification, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • In golang, gin framework accesses jwt and uses token to verify identity
  • Go gin+token (JWT) verification to achieve login verification
  • Golang web development based on gin authentication tool jwt
  • Definition requirements and analysis of using JWT in gin framework

<<:  Detailed explanation of small state management based on React Hooks

>>:  Deep understanding of the use of ::before/:before and ::after/:after

Recommend

How to upgrade https under Nginx

Purchase Certificate You can purchase it from Ali...

VMware Workstation 14 Pro installation Ubuntu 16.04 tutorial

This article records the specific method of insta...

Native js to implement 2048 game

2048 mini game, for your reference, the specific ...

Web Standard Application: Redesign of Tencent QQ Home Page

Tencent QQ’s homepage has been redesigned, and Web...

Mycli is a must-have tool for MySQL command line enthusiasts

mycli MyCLI is a command line interface for MySQL...

How to install FastDFS in Docker

Pull the image docker pull season/fastdfs:1.2 Sta...

Use of Vue filters and custom instructions

Table of contents Filters 01.What is 02. How to d...

How to create Apache image using Dockerfile

Table of contents 1. Docker Image 2. Create an in...

Four completely different experiences in Apple Watch interaction design revealed

Today is still a case of Watch app design. I love...

How to design the homepage of Tudou.com

<br />I have been working in front-end for s...

Several common methods for passing additional parameters when submitting a form

When submitting a form, you may encounter situatio...

How to change the root password of Mysql5.7.10 on MAC

First, start MySQL in skip-grant-tables mode: mys...

How to disable ads in the terminal welcome message in Ubuntu Server

If you are using the latest Ubuntu Server version...