0

We have a requirement to allow a third party to authenticate to an Azure Web App and display an Azure AD secured Web App View non interactively.

The problem I am encountering is I can get a token, but when I try to request the required resource in Azure Web App with the token, I am getting a Page saying to Sign into my Account instead of the HTML content from Azure Web App.

I had developed the code following steps from the below picture

string aadInstance = "https://login.microsoftonline.com/{0}";
string tenant = "xxxx.onmicrosoft.com";
string clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
Uri redirectUri = new Uri(@"http://xxxxxDaemonAppDev");
string resourcePath = @"https://xxxxx.azurewebsites.net/Customer/CashSummary?term=xxxxxx";
string appIdURI = @"https://xxxxx.onmicrosoft.com/WebApp-xxxxx.azurewebsites.net";
AuthenticationContext authContext = null;
AuthenticationResult result = null;

authContext = new AuthenticationContext(authority, new FileCache());
UserCredential uc = new UserPasswordCredential("xxxx@jkintranet.com", "xxx@xxxx");

try
{
    //I am getting the Token here.
    result = authContext.AcquireTokenAsync(appIdURI, clientId, uc).Result;


    #region Call Web APP

    HttpClient httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    HttpResponseMessage response = httpClient.GetAsync(resourcePath).Result;


    if (response.IsSuccessStatusCode)
    {
        //I am not getting the HTML Content here
        string rezstring = response.Content.ReadAsStringAsync().Result;
        var todoArray = JArray.Parse(rezstring);
        Console.ForegroundColor = ConsoleColor.Green;
        foreach (var todo in todoArray)
        {
            Console.WriteLine(todo["Title"]);
        }
    }
    #endregion
}
catch (Exception ee)
{
    MessageBox.Show(ee.Message);
    return;
}

Tools and Technologies followed:

  1. Client App is a Daemon or Server Application to Web API
  2. Server App is a Web Azure Web App Secured with Azure AD authentication
  3. Both Server as Web APP and Client as Native are registered in Azure AD

The Architecture I followed:

enter image description here

Following the steps, I have written the code

The Web App's StartupAuth.cs has this:

public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            AppUserModelContext appUserDB = new AppUserModelContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            //Changed this from
            //app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Changed this to
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                //added this
                CookieSecure = CookieSecureOption.SameAsRequest,
                CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                    UseTokenLifetime = false,
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {

                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;
                            ClientCredential credential = new ClientCredential(clientId, appKey);
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                            AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                            //AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            //code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                            return Task.FromResult(0);
                        },

                        SecurityTokenValidated = (context) =>
                        {
                            var identity = context.AuthenticationTicket.Identity;
                            var identityName = context.AuthenticationTicket.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value;
                            var aIdentity = identityName.Split('@');
                            var appUser = appUserDB.Find(aIdentity[0]);

                            if (appUser == null)
                            {
                                context.AuthenticationTicket.Properties.RedirectUri = "/Account/SignOut";
                            }

                            //Add Claims-Company
                            context.AuthenticationTicket.Identity.AddClaim(
                                new System.Security.Claims.Claim(
                                        "http://com.jksb.org/claims/customclaims/company",
                                        "JKB",
                                        null,
                                        "LOCAL AUTHORITY"));

                            //Add Claims-Business Unit
                            context.AuthenticationTicket.Identity.AddClaim(
                                new System.Security.Claims.Claim(
                                        "http://com.jksb.org/claims/customclaims/buid",
                                        appUser.AppBuID,
                                        null,
                                        "LOCAL AUTHORITY"));


                            return Task.FromResult(0);
                        },

                        //added this
                        AuthenticationFailed = (context) =>
                        {
                            if (context.Exception.Message.StartsWith("OICE_20004") || context.Exception.Message.Contains("IDX10311"))
                            {
                                context.SkipToNextMiddleware();
                                return Task.FromResult(0);
                            }
                            return Task.FromResult(0);
                        }

                    },
        }
hiFI
  • 1,887
  • 3
  • 28
  • 57

0 Answers0