编程语言
首页 > 编程语言> > c# – WebApi和ADFS集成

c# – WebApi和ADFS集成

作者:互联网

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

     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标头).我不确定我错过了什么.

还有一点需要注意:当我被提示输入我的凭据时,我得到下面的对话框,而不是我使用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控制器进行一次http调用到使用Authorize修饰的值控制器使用教程中的以下代码进行属性:

 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答案,看来我将无法做我希望做的事情(使用On-Premise ADFS的WebApi后端的AngularJS应用程序).我决定使用MVC-AngularJS方法.

标签:c,asp-net-web-api,oauth-2-0,adfs
来源: https://codeday.me/bug/20190711/1430206.html