asp.net-mvc – 401在MVC API中使用Microsoft Azure Active Directory验证OAuth 2.0承载令牌时

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 401在MVC API中使用Microsoft Azure Active Directory验证OAuth 2.0承载令牌时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在MVC中编写API服务(没有视图,只是API),我想使用通过client_credentials流程(2-legged OAuth)获取的OAuth 2.0令牌.我在Azure管理门户中创建了一个ActiveDirectory应用程序,并成功获得了一个不记名令牌(请参见底部Postman的截图).

然后我安装了Microsoft.Owin.Security.ActiveDirectory nuget包,创建了一个Owin启动类并在其中编写了以下代码

  1. public class OwinStartup
  2. {
  3. public void Configuration(IAppBuilder app)
  4. {
  5. // For more information on how to configure your application,visit http://go.microsoft.com/fwlink/?LinkID=316888
  6. var myoptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions();
  7. myoptions.Audience = // my App ID
  8. myoptions.Tenant = // my tenant
  9. myoptions.AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive;
  10. app.UseWindowsAzureActiveDirectoryBearerAuthentication(myoptions);
  11. }
  12. }

添加了一个带有动作的控制器,我希望可以使用不记名令牌访问该动作.

这是控制器:

  1. public class TestController : Controller
  2. {
  3. [Authorize]
  4. public JsonResult Index()
  5. {
  6. return Json(3,JsonRequestBehavior.AllowGet);
  7. }
  8. }

我试图用这样的Authorization标题调用它:

但是,我得到401:“您无权查看此目录或页面”.细节是:

  1. Module ManagedPipelineHandler
  2. Notification ExecuteRequestHandler
  3. Handler System.Web.Mvc.MvcHandler
  4. Error Code 0x00000000
  5. Requested URL http://localhost:57872/test
  6. logon Method Anonymous
  7. logon User Anonymous

它看起来我的持票人令牌被忽略了.

我究竟做错了什么?

附录:使用client_credentials流在Postman中创建Azure Active Directory OAuth承载令牌:

解决方法

似乎我可以通过在AD中创建第二个应用程序 – 客户端应用程序,将其授权给服务应用程序,并将身份验证令牌作为客户端而不是服务来请求它.

因此,在令牌请求中,我必须使用客户端应用程序的ID和秘密而不是原始ID,并添加另一个参数:“resource”,其值为服务应用程序ID:https://mytenant.onmicrosoft.com/servieappname

我的解决方案是基于微软的this good example.通过充当客户端的Web应用程序替换Windows应用商店应用.

猜你在找的asp.Net相关文章