2016-08-03 43 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方法。