如何清除Indy TIdHTTP BasicAuthentication凭据?

时间:2015-05-06 12:29:18

标签: delphi indy idhttp

我正在使用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;

2 个答案:

答案 0 :(得分:3)

您应该在每个请求上设置Request.UserNameRequest.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为止,以先发生者为准。

答案 1 :(得分:2)

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

  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;