2016-08-03 130 views
4

我創建了一個「測試」項目,我正在使用.Net 4.6 WebApi,我想要使用ADFS集成身份驗證 - 類似於this post。我打電話從一個角度項目的API和使用下面的代碼,我就能拿到認證頭:WebApi和ADFS集成

 string authority = ConfigurationManager.AppSettings["adfsEndpoint"].ToString(); 
    string resourceURI = "https://localhost:44388/"; 
    string clientID = "someguid"; 
    string clientReturnURI = "http://localhost:55695/"; 

    var ac = new AuthenticationContext(authority, false); 

    //This seems to be working as I am getting a token back after successful authentication 
    var ar = await ac.AcquireTokenAsync(resourceURI, clientID, new Uri(clientReturnURI), new PlatformParameters(PromptBehavior.Auto)); 
    string authHeader = ar.CreateAuthorizationHeader(); 

    //this fails with a 401 
    var client = new HttpClient(); 
    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:64038/api/Values"); 
    request.Headers.TryAddWithoutValidation("Authorization", authHeader); 
    var response = await client.SendAsync(request); 

    return response ; 

然而,在我的ValuesController的後續調用正在使用該授權屬性,我總是收到401 Unathorized迴應(即使我通過授權標題)。我不確定我錯過了什麼。

還有一件事要注意:當我被提示輸入憑據時,我得到下面的對話框,而不是我使用ADFS進行身份驗證的正常MVC應用程序獲得的典型ADFS登錄頁面(我不確定爲什麼會這樣也可能發生)。 enter image description here

回答

0

唉!結果發現我錯過這一段代碼,需要在ConfigureAuth方法:

app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions 
{ 
    Audience = ConfigurationManager.AppSettings["ida:Audience"], 
    MetadataEndpoint = ConfigurationManager.AppSettings["ida:MetadataEndpoint"] 
}); 

一旦添加此並提出在web.config文件中的必要的配置(和校正傳遞到AcquireTokenAsync方法resourceUri變量) ,我能夠從我的API控制器到值控制器,裝飾着用這個代碼從教程中的授權屬性發出HTTP調用:

var client = new HttpClient(); 
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:64038/api/Values"); 
request.Headers.TryAddWithoutValidation("Authorization", authHeader); 
var response = await client.SendAsync(request); 
string responseString = await response.Content.ReadAsStringAsync(); 
return responseString; 

這仍然不是一個AngularJS客戶合作(這我現在明白了),所以我會考慮爲此實現ADAL JS庫。

編輯

事實證明,基於this答案,看來我不能做什麼,我希望做的(使用的WebAPI後端使用內部部署ADFS AngularJS應用程序)。我決定改用MVC-AngularJS方法。