c# - WebApi 和 ADFS 集成

标签 c# asp.net-web-api oauth-2.0 adfs

我创建了一个“测试”项目,我在其中使用 .Net 4.6 WebApi,我想使用 ADFS 集成身份验证 - 类似于 this post .我从一个角度项目调用 api 并使用以下代码我能够获得授权 header :

     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 ;

但是,在使用 Authorize 属性对我的 ValuesController 进行后续调用时,我总是会收到 401 Unathorized 响应(即使我正在传递 Authorization header )。我不确定我错过了什么。

另一件需要注意的事情:当我被提示输入我的凭据时,我得到下面的对话框,而不是我使用 ADFS 进行身份验证的普通 MVC 应用程序获得的典型 ADFS 登录页面(我不确定为什么会发生这种情况任何一个)。 enter image description here

最佳答案

呃!原来我错过了 ConfigureAuth 方法中需要的这段代码:

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

一旦我添加了它并在 web.config 文件中进行了必要的配置(并更正了传递给 AcquireTokenAsync 方法的 resourceUri 变量),我就能够从我的 api Controller 向被装饰的值 Controller 进行 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回答,看来我将无法做我希望做的事情(AngularJS 应用程序使用 WebApi 后端使用 On-Premise ADFS)。我决定改用 MVC-AngularJS 方法。

关于c# - WebApi 和 ADFS 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38747576/

相关文章:

oauth-2.0 - Google 服务帐户和工作表权限

javascript - 如何实际使用使用discord oauth2请求的数据

c# - WPF 资源未加载?

C# 为单个事件处理程序动态生成按钮

c# - Web API 获取在 Controller 上进行 UrlEncoded 的请求参数

c# - 如何在 web api 中发送两个对象作为响应消息和响应代码

c# - WebGrid 分页不工作

c# - 以 DataGrid 作为左侧组件的 GridSplitter

Java REST Web 服务或 .Net Web API

javascript - 您能否在不征求用户允许的情况下使用 Graph API 获取公共(public) Facebook 页面的提要?