使用令牌访问Azure AD安全Web App视图

时间:2018-03-06 09:58:16

标签: c# azure azure-active-directory

我们要求允许第三方对Azure Web App进行身份验证,并以非交互方式显示Azure AD安全Web App视图。

我遇到的问题是我可以获得令牌,但当我尝试使用令牌在Azure Web App中请求所需资源时,我收到一个页面说登录我的帐户而不是Azure Web App中的HTML内容。

我根据下图中的步骤开发了代码

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

随后的工具和技术:

  1. 客户端应用是Daemon or Server Application to Web API
  2. Server App是使用Azure AD身份验证保护的Web Azure Web App
  3. 作为 Web APP 的服务器和作为 Native 的客户端都在Azure AD中注册
  4. 我遵循的架构:

    enter image description here

    按照步骤,我编写了代码

    Web App的StartupAuth.cs有:

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

0 个答案:

没有答案
相关问题