1

我正在使用 Indy TIdHTTP 获取带有 BasicAuthentication 的请求。

代码工作正常,但 TIdHTTP 在第一个 401 之后不会清除 BasicAuthentication 凭据,如果用户使用正确的登录密码重新输入凭据并再次发送请求。用户必须登录两次才能授权。

用户操作顺序:

步骤 1. 用户输入错误的登录密码:ResponseCode = 401

步骤 2. 用户类型正确的登录密码:ResponseCode = 401

步骤 3. 用户类型正确的登录密码:ResponseCode = 200

我认为第 2 步的结果是一个错误。我应该怎么办?

简单代码:

var
IdHTTP1: TIdHTTP;

fLogin : string;
fPassword : string;

/// ...

if ( fLogin <> '' ) and ( fPassword <> '' )
  then
    begin
    if ( IdHTTP1.Request.Username <> fLogin )
        or
       ( IdHTTP1.Request.Password <> fPassword )
      then
        begin  
          IdHTTP1.Request.BasicAuthentication := True;
          IdHTTP1.Request.Username := fLogin;
          IdHTTP1.Request.Password := fPassword;
        end;

      s := IdHTTP1.Get( 'some_url' );          
      response_code := Idhttp1.response.ResponseCode;

      case response_code of
        200:
          begin
               // parse request data
          end;
        401 : Result := nc_res_Auth_Fail;
        else Result := nc_res_Fail;
       end;
end;
4

2 回答 2

4

您应该在更改之前清除您的身份验证

  if Assigned(IdHTTP1.Request.Authentication) then
    begin
      IdHTTP1.Request.Authentication.Free;
      IdHTTP1.Request.Authentication:=nil;
    end;

或者你可以这样改变

  if Assigned(IdHTTP1.Request.Authentication) then
    begin
      IdHTTP1.Request.Authentication.Username:=...;
      IdHTTP1.Request.Authentication.Password:=...;
    end else
    begin
      IdHTTP1.Request.BasicAuthentication:=True;
      IdHTTP1.Request.Username:=...;
      IdHTTP1.Request.Password:=...;
    end;
于 2015-05-06T13:18:59.520 回答
3

您应该在每个请求上设置Request.UserNameandRequest.Password属性,然后OnAuthorization在服务器要求时使用该事件来检索新凭据,例如:

procedure TSomeClass.HttpAuthorization(Sender: TObject; Authentication: TIdAuthentication; var Handled: Boolean);
begin
  if GetNewCredentials() then
  begin
    Authentication.UserName := ...;
    Authentication.Password := ...;
    Handled := True;
  end;
end;

//...

var
  IdHTTP1: TIdHTTP;
  fLogin : string;
  fPassword : string;

// ...

  IdHTTP1.OnAuthorization := HttpAuthorization;

  IdHTTP1.Request.BasicAuthentication := True;
  IdHTTP1.Request.Username := fLogin;
  IdHTTP1.Request.Password := fPassword;

  s := IdHTTP1.Get( 'some_url' );          
  response_code := IdHTTP1.Response.ResponseCode;

  case Response_Code of
    200:
      begin
        // parse request data
      end;
    401 : Result := nc_res_Auth_Fail;
  else
    Result := nc_res_Fail;
  end;
end;

TIdHTTP将在内部不断重新尝试登录,OnAuthorization每次触发,直到服务器停止发送 401 回复或TIdHTTP.MaxAuthRetries已到达,以先发生者为准。

于 2015-05-06T16:12:28.927 回答