使用Azure AD v2.0进行保护时,在[授权]修饰的Web API方法上获取404

时间:2017-10-18 06:14:49

标签: c# asp.net azure core

在我的方案中,我有一个Windows UWP客户端应用程序,用于验证用户并使用OAuth 2.0访问令牌和Azure AD v2.0端点访问受保护的Web API服务。 Web API使用ASP.NET Core 2.0构建。我无法在Azure样本GitHub上找到具有确切配置的任何现有样本,因此我决定自己构建它。我能够对用户进行身份验证并访问Microsoft Graph以获取用户的配置文件,但是当我尝试访问Web API时,我收到了404 Not Found错误消息。相同Web API的不安全方法(没有[授权]修饰)可以正常工作。

Web API的My Startup.cs包含以下段:

        // Add Authentication scheme properties.
        services.AddAuthentication(options => {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        });


        string clientId = Configuration["AzureAd:ClientId"];
        string redirectUri = Configuration["AzureAd:RedirectUri"];
        string tenant = Configuration["AzureAd:Tenant"];

        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture,
                        Configuration["AzureAd:AadInstance"], tenant);

        //OpenID Connect (OIDC) Authentication
        services.AddAuthentication(options => {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(options => {
                options.ClientId = clientId;
                options.Authority = authority;
                options.SignedOutRedirectUri = redirectUri;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
                options.Events = new OpenIdConnectEvents
                {
                    OnRemoteFailure = OnRemoteFailure,
                    OnTokenValidated = OnTokenValidated
                };
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false
                };
            });

其中appsettings.json配置了从ClientID App Registration复制的apps.dev.microsoft.com,以及 Tenant = "common"RedirectUri points to https://localhost:44353/signin-oidcAadInstance is set to: https://login.microsoftonline.com/{0}/oauth2/v2.0

然后,我的客户端UWP应用程序配置了相应的设置:

    private static string ClientId = "436b73b7-XXXXXXXXX";
    private const string tenant = "common";
    private static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture,
        "https://login.microsoftonline.com/{0}/oauth2/v2.0", tenant);

    public static PublicClientApplication PublicClientApp = new PublicClientApplication(ClientId, authority);

Microsoft Graph和自定义API的API端点配置如下:

    string _sppAPIEndpoint = "https://localhost:44357/api/AAD/secure";
    string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me";

并且范围设置为访问身份验证:

    //Set the scope for API call to user.read
    string[] _scopes = new string[] { "user.read" };

所以,当我运行UWP应用程序时,我可以获得身份验证令牌和图表信息,但是,正如我在开头说的那样,当我执行以下命令时,我得到了404:

        var httpClient = new System.Net.Http.HttpClient();
        var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
        //Add the token in Authorization header
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            HttpResponseMessage response = await httpClient.GetAsync(url);

对于令牌值,我试图同时使用AccessToken和IdpToken。

我做错了什么?任何提示和指示将不胜感激。

3 个答案:

答案 0 :(得分:0)

有很多样本,但是如果你发现一个缺失,它可能会弹出。 您最接近的是:WPF Application to WebAPI with ASP.NET Core

最后,您必须在“融合应用程序”部分下至少拥有两个应用程序,如下所示:

enter image description here

然后,您需要显式地对UWP应用程序访问API。这是通过传递UWP应用程序的客户端ID在API应用程序中完成的:

enter image description here

然后,您的UWP App将为API创建身份验证请求作为资源,并将接收用于API的访问令牌。

如果要获取多资源令牌(要使用Microsoft Graph的标记用于WebAPI,则必须创建多资源请求。

您还可以尝试在请求中包含您的API范围(请查看我的第二个屏幕截图 - API的SCOPE,您可以定义自己的范围)。

答案 1 :(得分:0)

astaykov ,谢谢。遗憾的是,链接中的代码示例是指ADv1 B2B实现,而不是v2。此外,我做了你所做的一切:为客户创建了第二个应用程序注册(虽然所有文档都告诉所有客户使用一个应用程序注册),并添加了预授权的应用程序条目:

Adv2 settings

我甚至在我的客户端请求中添加了一个新范围,其中包含Native app Id: "api://436b73b7-8f59-45e7-9449-580fb9a5d90d/access_as_user",但是当我尝试使用新令牌调用API时,我收到UI屏幕上显示的错误消息:

UI Screenshot with a response message

答案 2 :(得分:0)

HTTP 404表示客户端能够与给定服务器通信,但服务器无法找到所请求的内容。

请检查提供相应服务的服务器的URL是否正确。