Adal.js and Azure AD secured web API - Access SharePoint with user context

Brass Contributor

We have an Azure AD authenticated web API. We successfully retrieve authentication token via Adal.JS and authenticate against the web API controllers marked with Authorize attribute. However, we would like for some controllers to create a SharePoint user context with the TokenHelper by passing the authorization code. We are receiving bad request error. Here is the code:

var authCode = System.Web.HttpContext.Current.Request.Headers["Authorization"].Replace("Bearer", String.Empty).Trim();

var authRealm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteCollectionUrl));

var redirectUri = new Uri(siteCollectionUrl);

using (var clientContext =
TokenHelper.GetClientContextWithAuthorizationCode(siteCollectionUrl, TokenHelper.SharePointPrincipal, authCode, authRealm, redirectUri))...


siteCollectionUrl is added to native app's redirect uris with a wildcard (we also tried without wildcard) - note that we pass it as a part of the redirectUri

 

Currently we are successfully creating an app only context within the web api controllers - we have provided the Azure Web API access to the site collection.

 

Update we have tried the following approaches without success:

using (var clientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAzureADNativeApplicationAuthenticatedContext(siteCollectionUrl, "NativeAppClientId", siteCollectionUrl))
using (var clientContext = new OfficeDevPnP.Core.GetAzureADAccessTokenAuthenticatedContext(siteCollectionUrl, authCode)

We have also decoded the authorization code to its JSON format and passed the pure string without success (with a helper classes taken from here: https://blogs.msdn.microsoft.com/kaevans/2013/08/25/creating-a-fiddler-extension-for-sharepoint-2013...).

 

We have added access to the native app to SharePoint in the Azure AD.

 

Anyone could help with this?

1 Reply

On further inspection we have noticed that the request was throwing an error

 

{x-ms-diagnostics: 3000003;reason="Invalid audience Uri 'Audience URI as specified in webApiAppIdUri'.";category="invalid_client"
SPRequestGuid: 32439d9d-408d-3000-2140-22c0c88730a5
request-id: 32439d9d-408d-3000-2140-22c0c88730a5
Strict-Transport-Security: max-age=31536000
X-FRAME-OPTIONS: SAMEORIGIN
SPRequestDuration: 12
SPIisLatency: 2
MicrosoftSharePointTeamServices: 16.0.0.5611
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
Date: DATE IN GMT
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
Server: Microsoft-IIS/8.5
WWW-Authenticate: Bearer realm="TENANT GUID",client_id="00000003-0000-0ff1-ce00-000000000000",trusted_issuers="00000001-0000-0000-c000-000000000000@*,https://sts.windows.net/*/,00000003-0000-0ff1-ce00-000000000000@90140122-8516-11e1-8eff-49304924019b",authorization_uri="https://login.windows.net/common/oauth2/authorize"
X-Powered-By: ASP.NET
}

We have given the native app and the web app permissions to all SharePoint sites.

We have defined the endpoints object in the ADAL.js config as follows:

var endpoints = {};
this.adalEndPoints[_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists"] = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists"; // here we have tried different permutations
...
// ADAL endpoints for automatic hooking
endpoints: 

 

And here is a simple C# web client for testing purposes we have made:

string result = String.Empty;
            string requestUri = OfficeDevPnP.Core.Utilities.UrlUtility.Combine(siteCollectionUrl, "_api/web/lists");
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(siteCollectionUrl);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);

                    var request = httpClient.GetAsync(requestUri).Result;
                    request.EnsureSuccessStatusCode();
                    if (request.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        result = request.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch(Exception ex)
            {

            }

            return result;

 

Anybody could point me to a solution?