微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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方法.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐