Skip to content

open-resty doc

doc

access_by_lua

lua
-- access_by_lua
local jwt = ngx.var.cookie_access_token
local ids = "https://login.example.com/auth"
local appid = "123456"

if not jwt then
  local redirect_uri = ngx.escape_uri(ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.request_uri)
  return ngx.redirect(ids .. "?redirect_uri=" .. redirect_uri .. "&appid=" .. appid)
end
lua
-- callback.lua
local http = require "resty.http"
local auth_url = "https://auth.example.com/token"

local code = ngx.var.arg_code
local res = http.new():request_uri(auth_url, {
  method = "POST",
  body = ngx.encode_args({
    grant_type = "authorization_code",
    code = code,
    client_id = "...",
    client_secret = "..."
  }),
  headers = {
    ["Content-Type"] = "application/x-www-form-urlencoded"
  }
})

-- 得到 JWT
lua
ngx.header["Set-Cookie"] =
  "access_token=" .. jwt ..
  "; Path=/; HttpOnly; Secure; SameSite=Lax"
lua
local jwt = require "resty.jwt"

local token = ngx.var.cookie_access_token
local obj = jwt:verify("secret", token)

if not obj.verified then
  return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end