简体   繁体   中英

Getting 404 on the [Authorize] decorated Web API method when securing with Azure AD v2.0

In my scenario I have a Windows UWP Client app authenticating user and accessing the protected Web API service using OAuth 2.0 access tokens and Azure AD v2.0 endpoint. The Web API is built with ASP.NET Core 2.0. I couldn't find any existing samples on Azure samples GitHub with the exact configuration, so I've decided to build it myself. I was able to authenticate user and access the Microsoft Graph to get the user's profile, but when I try to access a Web API, I'm getting the 404 Not Found Error Message. The unsecured methods (without [Authorize] decoration) of the same Web API works fine.

My Startup.cs of the Web API contains this segment:

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

where the appsettings.json is configured with the ClientID copied from the apps.dev.microsoft.com App Registration, and the Tenant = "common" . RedirectUri points to https://localhost:44353/signin-oidc and AadInstance is set to: https://login.microsoftonline.com/{0}/oauth2/v2.0

Then, my client UWP app is configured with the corresponding settings:

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

The API endpoints for both Microsoft Graph and the custom API are configured like this:

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

And the scope is set to access authentication:

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

So, when I run the UWP app, I can get the auth token, and the Graph info, but, like I said in the beginning, I am getting the 404 when I execute the following commands:

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

For the token value I've tried to use both the AccessToken and the IdpToken with no avail.

What am I doing wrong? Any tips and pointers will be greatly appreciated.

There are a lot of samples, but if you find one missing, it will probably popp-up. The closest you need is here: WPF Application to WebAPI with ASP.NET Core .

At the end you must have at least two applications under the "Converged Applications" section like this:

在此处输入图片说明

Then, you need to explicitly grand the UWP application access to the API one. This is is done within the API application by passing the client ID for the UWP app:

在此处输入图片说明

Then you UWP App shall create authentication request for the API as resource and will receive the an Access Token for use with the API.

If you want to get a multi-resource token (to use the token for Microsoft Graph and for the WebAPI, you have to create a multi-resource request.

You can also try including your API scope (check my second screenshot - there is the SCOPE for the API and you can define your own scopes) in the request.

astaykov , thanks. Unfortunately, the code sample in your link refers to the ADv1 B2B implementation, not v2. Also, I did all you suggested: created a second app registration for the client (though all documentation is telling to use one single app registration for all clients), and added pre-authorized application entry:

Adv2 settings

I even added a new scope to my client request, which contains the Native app Id: "api://436b73b7-8f59-45e7-9449-580fb9a5d90d/access_as_user" , but when I tried to call the API with a new Token, I receive the error message shown on the UI screen:

UI Screenshot with a response message

The HTTP 404 indicates that the client was able to communicate with a given server, but the server could not find what was requested.

Please check the URL is correct for the server providing the corresponding service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM