加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WebApi和ADFS集成

发布时间:2020-12-15 21:01:25 所属栏目:百科 来源:网络整理
导读:我创建了一个“测试”项目,我正在使用.Net 4.6 WebApi,我希望使用ADFS集成身份验证 – 类似于 this post.我从一个角度项目调用api并使用以下代码我是能够获得授权标题: string authority = ConfigurationManager.AppSettings["adfsEndpoint"].ToString(); s
我创建了一个“测试”项目,我正在使用.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方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读