我正在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 持有者令牌: