gpt4 book ai didi

asp.net-mvc - 在 MVC API 中使用 Microsoft Azure Active Directory 验证 OAuth 2.0 不记名 token 时出现 401

转载 作者:行者123 更新时间:2023-12-04 12:31:26 27 4
gpt4 key购买 nike

我正在 MVC 中编写一个 API 服务(没有 View ,只有 API),并且我想使用通过 client_credentials 流获取的 OAuth 2.0 token (2-有腿 OAuth)。我在 Azure 管理门户中创建了一个 ActiveDirectory 应用程序,并成功获取了不记名 token (请参阅底部 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);
}
}

我添加了一个带有操作的 Controller ,并且我希望可以使用不记名 token 访问该操作。

这是 Controller :

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

我尝试使用授权 header 来调用它,如下所示:

Calling endpoint

但是,我收到 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

看起来我的不记名 token 被忽略了。

我做错了什么?

<小时/>

附录:使用 client_credentials 流程在 Postman 中创建 Azure Active Directory OAuth 不记名 token :

Creating a token in Postman

最佳答案

看来我可以通过在 AD 中创建第二个应用程序 - 客户端应用程序,将其授权给服务应用程序,并作为客户端而不是服务请求身份验证 token 来使其工作。

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

我的解决方案基于 this good example由微软。将 Windows 应用商店应用替换为充当客户端的 Web 应用。

关于asp.net-mvc - 在 MVC API 中使用 Microsoft Azure Active Directory 验证 OAuth 2.0 不记名 token 时出现 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26118671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com