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启动类并在其中编写了以下代码

public class OwinStartup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application,visit http://go.microsoft.com/fwlink/?LinkID=316888
        var myoptions = new WindowsAzureActiveDirectoryBearerAuthenticationoptions();
        myoptions.Audience = // my App ID
        myoptions.Tenant = // my tenant
        myoptions.AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive;
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(myoptions);
    }
}

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

这是控制器:

public class TestController : Controller
{
    [Authorize]
    public JsonResult Index()
    {
        return Json(3,JsonRequestBehavior.AllowGet);
    }
}

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

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

Module     ManagedPipelineHandler
Notification       ExecuteRequestHandler
Handler    System.Web.Mvc.MvcHandler
Error Code     0x00000000
Requested URL      http://localhost:57872/test
logon Method       Anonymous
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应用商店应用.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....