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

Delphi 10.2 ISAPI DLL读取Authorization Bearer请求头异常问题

Delphi 10.2 ISAPI DLL读取Authorization Bearer字段解决方案

ISAPI环境下的TWebRequest.Authorization属性仅默认解析Basic类型的认证头,Bearer类型不会被自动填充,需通过以下方式手动处理:

1. 直接读取原始请求头

在TWebModule1.WebModuleBeforeDispatch事件中,使用Request.GetFieldByName('Authorization')获取完整的认证头内容,该方法不会过滤认证类型,能直接拿到Bearer格式的头信息。

2. 解析并验证Bearer令牌

复用你已有的JWT解码逻辑,从完整认证头中提取令牌并验证,示例代码如下:

procedure TWebModule1.WebModuleBeforeDispatch(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  AuthHeader: string;
  AuthParts: TStringList;
  AuthType, AuthData: string;
  VUsername, VPassword: string;
  IsAuthenticated: Boolean;
begin
  // 读取完整Authorization请求头
  AuthHeader := Request.GetFieldByName('Authorization');
  if AuthHeader.IsEmpty then
  begin
    Response.StatusCode := 401;
    Response.Content := 'Authorization header required';
    Handled := True;
    Exit;
  end;

  // 拆分认证类型与令牌数据
  AuthParts := TStringList.Create;
  try
    AuthParts.Delimiter := ' ';
    AuthParts.StrictDelimiter := True;
    AuthParts.DelimitedText := AuthHeader;
    
    if AuthParts.Count < 2 then
    begin
      Response.StatusCode := 400;
      Response.Content := 'Invalid Authorization header format';
      Handled := True;
      Exit;
    end;

    AuthType := AuthParts[0];
    AuthData := AuthParts[1];

    // 调用认证解析逻辑
    IsAuthenticated := DoParseAuthentication(nil, AuthType, AuthData, VUsername, VPassword);
    if not IsAuthenticated then
    begin
      Response.StatusCode := 401;
      Response.Content := 'Unauthorized';
      Handled := True;
      Exit;
    end;
  finally
    AuthParts.Free;
  end;

  // 认证通过,继续处理请求
end;

// 复用调整后的认证解析函数
function TWebModule1.DoParseAuthentication(ASender: TIdContext; const AAuthType,
  AAuthData: String; var VUsername, VPassword: String): Boolean;
var
  s, __BaseName, __GuidBase: String;
begin
  Result := False;
  if TextIsSame(AAuthType, 'Basic') then
  begin
    with TIdDecoderMIME.Create do
    try
      s := DecodeString(AAuthData);
    finally
      Free;
    end;
    VUsername := Fetch(s, ':');
    VPassword := s;
    Result := True;
  end
  else if TextIsSame(AAuthType, 'Bearer') then
  begin
    // Bearer令牌无需Base64解码,直接传入JWT验证逻辑
    if Tjwt.Decodejwt_Bearer(AAuthData, __BaseName, __GuidBase) then
    begin
      // 此处可添加额外的令牌有效性验证逻辑
      Result := True;
    end;
  end;
end;

关键注意事项

  • Bearer格式的JWT令牌本身是Base64URL编码,无需额外调用TIdDecoderMIME.DecodeString,直接传入你的Decodejwt_Bearer方法即可。
  • 验证失败时需返回401状态码并标记Handled := True,终止后续请求处理流程。

内容的提问来源于stack exchange,提问作者Bill.Parish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:27:28