1

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.

3
  • One thing to check is the actual token; you can paste your token in jwt.io and check the issuer and authority as well as the intended audience and scopes. That way you can check if the token you receive is actually going to work with your settings. Commented Oct 18, 2017 at 6:19
  • @bartbje, I just did, what you've suggested and when I paste it into jwt.io, I've got this info: PAYLOAD:DATA { "ver": "2.0", "iss": "login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/…", ... "exp": 1508352301, "iat": 1508348401, "nbf": 1508348401, "name": "Danny Garber", "preferred_username": "XXXXX", "oid": "XXX", "tid": "XXX", "azp": "XXX", "scp": "access_as_user", "azpacr": "0", "aio": "XXX" } So, it looks like the right token to me, but the api calls still comes with either 404 Commented Oct 18, 2017 at 17:54
  • @DannyGarber did you get a resolution to this? Exact same problem over here and very confused. Commented Nov 27, 2020 at 19:29

2 Answers 2

0

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:

enter image description here

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:

enter image description here

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The sample code you've provided in your answer is not relevant to my scenario. It uses the ADAL with AD v1, and I use the latest MSAL with AD v2 endpoint. Yesterday, I managed at some point to get UWP client authenticated and access API, but I've noticed a strength behavior doing that. These apps would work and talk to each other only when I have the Fiddler app running side-by-side capturing HTTPS requests. The moment I stop Fiddler, I get the "infamous" error back saying: "The certificate authority is invalid or incorrect." Any idea?
I was able to fix the error "The certificate authority is invalid or incorrect", by exporting and adding the IIS Express Developer certificate to the Trusted Root Certification Authorities. However, the main issue I've started this thread hasn't been yet resolved. Now, when I call API, I receive in response the HTML content for log into my AD tenant. It looks that it doesn't see my token in the API request.
-1

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.

1 Comment

The URL is correct. I could access it if I remove [Authorize] declaration from the controller class. The problem I'm having is that I can't reach out the API without Fiddler app capturing HTTPS requests. (See my other comment below)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.