2017-05-09 109 views
1

我在寫一個Windows應用程序,它將與Web API進行通信。以下是我如何撥打電話:服務器上的Web API認證

HttpClient client = null; 
     HttpClientHandler handler = new HttpClientHandler() { PreAuthenticate = true, Credentials = CredentialCache.DefaultCredentials }; 
     client = new HttpClient(); 
     client.BaseAddress = new Uri(apiBaseAddress); 
     var byteArray = Encoding.ASCII.GetBytes(Environment.UserName); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); 
     HttpResponseMessage response = client.GetAsync("api/Tickets/AuthenticateUser").Result; 

我傳遞當前記錄的憑據。我寫了一個過濾器連接到數據庫並檢查用戶名是否存在。代碼:

public class BasicAuthenticationWindowsAppAttribute : System.Web.Http.Filters..AuthorizationFilterAttribute 
{ 
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     if (actionContext.Request.Headers.Authorization == null) 
     { 
      actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 
     } 
     else 
     { 
      string authToken = actionContext.Request.Headers.Authorization.Parameter; 
      string Handle = Encoding.UTF8.GetString(Convert.FromBase64String(authToken)); 
      GenericIdentity gi = new GenericIdentity(Handle); 
      Thread.CurrentPrincipal = new GenericPrincipal(gi, null); 
      HttpContext.Current.User = Thread.CurrentPrincipal; 
      Amo_MasterDataEntities amoMasterDataContext = new Amo_MasterDataEntities(); 
      var query = from a in amoMasterDataContext.allassociatemasters 
         where a.Handle == Handle 
         select a; 
      //If Handle is present in AMOMasterData.AllAssociatemaster table 

      if (query.Count() > 0) 
      { 
       //TicketsController tc = new TicketsController(); 
       string assocId = "", fName ="", lName = ""; 
       bool authenticated = false; 
       foreach (var item in query) 
       { 
        assocId = item.AssociateID; 
        fName = item.FirstName; 
        lName = item.LastName; 
        authenticated = true; 
       } 
       AuthInfo info = new AuthInfo(); 
       info.AssociateId = assocId; 
       info.FirstName = fName; 
       info.LastName = lName; 
       info.IsAuthenticated = authenticated; 
       actionContext.Request.Properties.Add(new KeyValuePair<string, object>("AuthInfo", info)); 
       base.OnAuthorization(actionContext); 

      } 
      //else return error 
      else 
      actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 

     } 
    } 
} 

當我在我的本地系統中運行Web服務時,它工作。但是當我在服務器上部署Web服務時,它會給我401 Unauhorized Message。

我已啓用基本和Windows身份驗證在IIS和Web.config文件中包含<authentication mode="Windows" />

編輯: 我能夠從那裏我已經部署了服務器訪問Web API方法。 但是當我從另一臺機器上的Windows客戶端調用Web API時,它將引發401錯誤。

我應該使用CORS嗎?如果是,請告訴我如何?

任何人都可以給我一個解決方案。

+0

如果你拿出'',那麼它會起作用嗎? –

+0

嗨馬克。我嘗試刪除仍然收到401. –

+0

您是否嘗試在OnAuthorization方法中引入任何類型的日誌記錄? –

回答

0

我找到了原因,..

我沒有經過處理程序的HttpClient的構造函數是問題。所以在上面的代碼替換:

client = new HttpClient(); 

有:

client = new HttpClient(handler); 

這樣一個愚蠢的錯誤。抱歉,添麻煩了。