2015-05-06 32 views
1

我使用Indy TIdHTTP獲取BasicAuthentication請求。如何清除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

你應該改變

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; 
+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已經達到了,以先發生者爲準。