本文介绍了401的MVC API在认证与微软Azure Active Directory中的OAuth 2.0承载令牌时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个MVC的 API服务(没意见,只是API),我想用通过收购client_credentials 的OAuth 2.0令牌流程(2-模式的OAuth)。我在Azure的管理门户创建一个 ActiveDirectory的应用,并成功收购了承载标记(见底部从邮差截图)。

I'm writing an API service in MVC (no views, just API), and I want to use OAuth 2.0 tokens acquired via the client_credentials flow (2-legged OAuth). I created an ActiveDirectory app in the Azure management portal, and have successfully acquired a bearer token (see screenshot from Postman at the bottom).

然后我安装了 Microsoft.Owin.Security.ActiveDirectory 的NuGet包,创建了一个Owin启动类,并在其中写了下面的code:

Then I installed the Microsoft.Owin.Security.ActiveDirectory nuget package, created an Owin startup class and wrote the following code in it:

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);
    }
}

我添加了一个控制器,一个动作,我想的行动与承载令牌访问。

I added a controller with an action, and I would like the action to be accessible with the bearer token.

这是控制器:

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

我试图与Authorization头这样来调用它:

I'm trying to call it with the Authorization header like this:

不过,我得到401:您没有权限查看该目录或页面。详情如下:

However, I'm getting 401: "You do not have permission to view this directory or page". The details are:

Module     ManagedPipelineHandler
Notification       ExecuteRequestHandler
Handler    System.Web.Mvc.MvcHandler
Error Code     0x00000000
Requested URL      http://localhost:57872/test
Logon Method       Anonymous
Logon User     Anonymous

看起来,我的承载令牌将被忽略。

It looks that my bearer token is ignored.

我在做什么错了?

附录:在创建一个邮差的Azure Active Directory中的OAuth承载令牌与client_credentials流:

Appendix: Creating an Azure Active Directory OAuth bearer token in Postman with the client_credentials flow:

推荐答案

我添加了以下属性控制器指挥它使用特定的
验证过滤器。

I added the following attribute to the controller directing it to use the specificauthentication filter.

[HostAuthentication("Bearer")]
public class someController:ApiController{
}

这篇关于401的MVC API在认证与微软Azure Active Directory中的OAuth 2.0承载令牌时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 22:54