You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

lua-resty-openidc中Authorize设置state时需检查会话已有state吗?

问题与分析

环境信息

  • lua-resty-openidc 版本:1.8.0
  • OpenID Connect 提供商:Spring Authorization Server

核心问题

在以下代码片段中:

local state = resty_string.to_hex(resty_random.bytes(16))

将state存入会话时,是否需要先检查会话中是否已存在state?

预期逻辑

  • 当会话中已存在state时,直接复用该state
  • 当会话中不存在state时,生成新的state并存入会话

相关完整代码

local function openidc_authorize(opts, session, target_url, prompt)
  local resty_random = require("resty.random")
  local resty_string = require("resty.string")
  local err

  -- 生成state和nonce
  local state = resty_string.to_hex(resty_random.bytes(16))
  local nonce = (opts.use_nonce == nil or opts.use_nonce)
    and resty_string.to_hex(resty_random.bytes(16))
  local code_verifier = opts.use_pkce and b64url(resty_random.bytes(32))

  -- 组装认证请求参数
  local params = {
    client_id = opts.client_id,
    response_type = "code",
    scope = opts.scope and opts.scope or "openid email profile",
    redirect_uri = openidc_get_redirect_uri(opts, session),
    state = state,
  }

  if nonce then
    params.nonce = nonce
  end

  if prompt then
    params.prompt = prompt
  end

  if opts.display then
    params.display = opts.display
  end

  if code_verifier then
    params.code_challenge_method = 'S256'
    params.code_challenge = openidc_s256(code_verifier)
  end

  if opts.response_mode then
    params.response_mode = opts.response_mode
  end

  -- 合并额外传入的参数
  if opts.authorization_params then
    for k, v in pairs(opts.authorization_params) do params[k] = v end
  end

  -- 将数据存入会话
  session:set("original_url", target_url)
  session:set("state", state)
  session:set("nonce", nonce)
  session:set("code_verifier", code_verifier)
  session:set("last_authenticated", ngx.time())

  if opts.lifecycle and opts.lifecycle.on_created then
    err = opts.lifecycle.on_created(session, params)
    if err then
      log(WARN, "`on_created` 处理器执行失败: " .. err)
      return err
    end
  end

  local res
  res, err = session:save()
  if err then
    log(WARN, "无法保存会话: " .. err)
  end

  -- 重定向到授权端点
  ngx.header["Cache-Control"] = "no-cache, no-store, max-age=0"
  return ngx.redirect(openidc_combine_uri(opts.discovery.authorization_endpoint, params))
end

内容的提问来源于stack exchange,提问作者bruce0828

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:40:57