public async Task<ActionResult> Authorize()
    {
      string authCode = Request.Params["code"];
      if (string.IsNullOrEmpty(authCode))
      {
        string error = Request.Params["error"];
        string error_description = Request.Params["error_description"];

        TempData["error_message"] = string.Format("Error: {0} - {1}", error, error_description);
        return RedirectToAction("Error");
      }

      AuthenticationContext authContext = new AuthenticationContext(authority);

      ClientCredential credential = new ClientCredential(appId, appSecret);
      AuthenticationResult authResult = null;
      Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

      try
      {
        authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(authCode, redirectUri, credential, scopes);
      }
      catch (AdalException ex)
      {
        TempData["error_message"] = ex.Message;
        return RedirectToAction("Error");
      }

      return Redirect("/");
    }
Esempio n. 2
0
        // Note the function signature is changed!
        public async Task<ActionResult> Authorize()
        {
            // Get the 'code' parameter from the Azure redirect
            string authCode = Request.Params["code"];

            string authority = "https://login.microsoftonline.com/common";
            string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"]; ;
            string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"]; ;
            AuthenticationContext authContext = new AuthenticationContext(authority);
            
            // The same url we specified in the auth code request
            Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

            // Use client ID and secret to establish app identity
            ClientCredential credential = new ClientCredential(clientId, clientSecret);

            try
            {
                // Get the token
                var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                    authCode, redirectUri, credential, scopes);

                // Save the token in the session
                Session["access_token"] = authResult.Token;
                
                // Try to get user info
                Session["user_email"] = GetUserEmail(authContext, clientId);

                return Redirect(Url.Action("Inbox", "Home", null, Request.Url.Scheme));
            }
            catch (AdalException ex)
            {
                return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
            }
        }
Esempio n. 3
0
        public async Task<IActionResult> Authorize()
        {
            // Get the 'code' parameter from the Azure redirect
            string authCode = Request.Query["code"];

            string authority = "https://login.microsoftonline.com/common";
            AuthenticationContext authContext = new AuthenticationContext(authority);

            // The same url we specified in the auth code request
            Uri redirectUri = new Uri(Url.Action("Authorize", "Outlook", null, "http"));

            // Use client ID and secret to establish app identity
            ClientCredential credential = new ClientCredential(ClientId, ClientSecret);

            try
            {
                // Get the token
                var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                    authCode, redirectUri, credential, scopes);

                // Save the token in the session
                Context.Session.SetString("access_token", authResult.Token);

                // Try to get user info
                Context.Session.SetString("user_email", GetUserEmail(authContext, ClientId));

                return Content("Access Token: " + authResult.Token);
            }
            catch (AdalException ex)
            {
                return Content($"ERROR retrieving token: {ex.Message}");
            }
        }
        public async Task<IActionResult> Complete(string code, string error, string error_description, string resource, string state) {
            var token = state;
            if(error.IsNotNullOrEmpty() || error_description.IsNotNullOrEmpty()) {
                _logger.Log(x => x.Error, () => string.Format("Error completing registration - {0}", new { token, error, error_description, resource, state }));
                return View("RegistrationError", new RegistrationErrorModel(error, error_description));
            }

            var registrationRequest = await _database.RegistrationRequests.FirstOrDefaultAsync(x => x.Token == state);

            if(registrationRequest == null) {
                _logger.Log(x => x.Error, () => string.Format("Unknown registration request - {0}", new { token }));
                return View("RegistrationRequestUnknown");
            }

            _logger.Log(x => x.Information, () => string.Format("Completing registration process - {0}", new { registrationRequest.Name, registrationRequest.Token }));

            var authority = AuthorityUrl.FormatUrlWith("common");

            var clientCredential = new ClientCredential(_settings.ClientID, _settings.ClientSecret);
            var authenticationContext = new AuthenticationContext(authority);
            var authenticationResult = authenticationContext.AcquireTokenByAuthorizationCode(code, new Uri(Request.GetUri().GetLeftPart(UriPartial.Path)), clientCredential);

            await RegisterAsync(registrationRequest.Name, authenticationResult.TenantId, authenticationResult.UserInfo.DisplayableId, authenticationResult.UserInfo.IdentityProvider);

            return View("TenantRegistrationSuccess");
        }
Esempio n. 5
0
        // GET: Discovery
        public ActionResult Index(string code)
        {
            AuthorizationContext authContext = new AuthorizationContext(
                ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common", true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);
        }
        public ClientKey(string clientId, ClientCredential clientCredential, Authenticator authenticator):this(clientId)
        {
            if (clientCredential == null)
            {
                throw new ArgumentNullException("clientCredential");
            }

            this.Authenticator = authenticator;
            this.Credential = clientCredential;
            this.HasCredential = true;
        }
        internal bool TryAddOrUpdateCredential(string traslatorName, ClientCredential clientCredential)
        {
            if (string.IsNullOrEmpty(traslatorName) || clientCredential == null || !clientCredential.IsValid)
                return false;

            if (_credentials.ContainsKey(traslatorName))
                _credentials[traslatorName] = clientCredential;
            else
                _credentials.Add(traslatorName, clientCredential);

            return true;
        }
    public async Task<ActionResult> Index()
    {

      // By using this version of the AuthenticationContext constructor,
      // we are using the default in-memory token cache. In a real app, you would
      // want to provide an implementation of TokenCache that saves the data somewhere
      // so that you could persist it if restarting the app, etc.
      AuthenticationContext authContext = new AuthenticationContext(authority);

      ClientCredential credential = new ClientCredential(appId, appSecret);
      AuthenticationResult authResult = null;

      ViewBag.Message = TempData["message"];

      try
      {
        authResult = await authContext.AcquireTokenSilentAsync(scopes, credential, UserIdentifier.AnyUser);

        ViewBag.UserName = GetUserEmail(authContext, appId);
      }
      catch (AdalException ex)
      {
        if (ex.ErrorCode == "failed_to_acquire_token_silently")
        {
          // We don't have a token in the cache OR the token couldn't be refreshed
          // We need to have the user sign in
          Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
          ViewBag.LoginUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, appId, redirectUri, UserIdentifier.AnyUser, null);
        }
        else
        {
          TempData["error_message"] = ex.Message;
          RedirectToAction("Error");
        }
      }

      return View();
    }
        public async Task<Client> ValidateClientCredentialsAsync(ClientCredential credential)
        {
            if (credential == null || credential.ClientId == null || credential.Secret == null)
            {
                throw new InvalidOperationException("credential is null");
            }

            var client = await _clients.FindClientByIdAsync(credential.ClientId);
            if (client == null || client.Enabled == false)
            {
                _logger.Error("Client not found in registry or not enabled: " + credential.ClientId);
                return null;
            }

            if (!ObfuscatingComparer.IsEqual(client.ClientSecret, credential.Secret))
            {
                _logger.Error("Invalid client secret: " + client.ClientId);
                return null;
            }

            _logger.InformationFormat("Client found in registry: {0} / {1}", client.ClientId, client.ClientName);
            return client;
        }
Esempio n. 10
0
        public void GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery()
        {
            //
            // The Client ID is used by the application to uniquely identify itself to Azure AD.
            // The App Key is a credential used by the application to authenticate to Azure AD.
            // The Tenant is the name of the Azure AD tenant in which this application is registered.
            // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
            // The Authority is the sign-in URL of the tenant.
            //
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant      = ConfigurationManager.AppSettings["ida:Tenant"];
            string clientId    = ConfigurationManager.AppSettings["ida:ClientId"];
            string appKey      = ConfigurationManager.AppSettings["ida:AppKey"];

            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            //
            // To authenticate to the To Do list service, the client needs to know the service's App ID URI.
            // To contact the To Do list service we need it's URL as well.
            //
            string appResourceId = ConfigurationManager.AppSettings["app:AppResourceId"];

            IContentKey contentKey = null;
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = null;
            IContentKeyAuthorizationPolicyOption policyOption = null;

            var authContext      = new AuthenticationContext(authority);
            var clientCredential = new ClientCredential(clientId, appKey);

            try
            {
                byte[] expectedKey = null;
                contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey, "GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery" + Guid.NewGuid().ToString());

                TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT);
                tokenRestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration");
                var    result         = authContext.AcquireToken(appResourceId, clientCredential);
                string jwtTokenString = result.AccessToken;

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                Assert.IsTrue(handler.CanReadToken(jwtTokenString));
                JwtSecurityToken token = handler.ReadToken(jwtTokenString) as JwtSecurityToken;
                Assert.IsNotNull(token);

                tokenRestrictionTemplate.Audience = token.Audiences.First();
                tokenRestrictionTemplate.Issuer   = token.Issuer;

                string optionName   = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication";
                string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate);
                policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted);

                List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption>
                {
                    policyOption
                };

                contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey);

                Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);
                Assert.IsNotNull(keyDeliveryServiceUri);

                // Enable once all accounts are enabled for per customer Key Delivery Urls
                //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId));

                KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed);
                byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString);

                string expectedString = GetString(expectedKey);
                string fetchedString  = GetString(key);
                Assert.AreEqual(expectedString, fetchedString);
            }
            finally
            {
                CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption);
            }
        }
        /// <summary>
        /// Returns an app-only token for the resource specified in <paramref name="resourceId"/> using the given <paramref name="clientId"/> and <paramref name="clientSecret"/>.
        /// </summary>
        /// <param name="resourceId">The resource identifier for which to return the token.</param>
        /// <param name="clientId">The client ID to use, i.e. the ID (guid) of the application.</param>
        /// <param name="clientSecret">The client secret or key to authenticate with.</param>
        /// <returns></returns>
        public static async Task <AuthenticationResult> AcquireAppOnlyTokenAsync(this AuthenticationContext authContext, string resourceId, string clientId, string clientSecret)
        {
            var cred = new ClientCredential(clientId, clientSecret);

            return(await authContext.AcquireTokenAsync(resourceId, cred));
        }
Esempio n. 12
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            // Configure session middleware.
            app.UseSession();

            app.UseCookieAuthentication();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions()
            {
                ClientId     = Configuration["Authentication:AzureAd:ClientId"],
                ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"],
                Authority    = Configuration["Authentication:AzureAd:AADInstance"] + "common",
                CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                GetClaimsFromUserInfoEndpoint = false,

                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = (context) =>
                    {
                        return(Task.FromResult(0));
                    },
                    OnAuthenticationFailed = (context) =>
                    {
                        context.Response.Redirect("/Home/Error");
                        context.HandleResponse(); // Suppress the exception
                        return(Task.FromResult(0));
                    },
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        // Exchange code for token using ADAL and save it into the token cache

                        // Either use tenant id with the token cache or clean the token cache each time user changes tenants or it will be confused
                        var tenantId    = (context.Ticket.Principal.FindFirst(AzureAdClaimTypes.TenantId))?.Value;
                        var clientCred  = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);
                        var authContext = new AuthenticationContext(context.Options.Authority.Replace("common", $"{tenantId}"), new NaiveSessionCache(tenantId, context.HttpContext.Session));
                        var authResult  = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, "https://graph.microsoft.com");
                        context.HandleCodeRedemption(authResult.AccessToken, authResult.IdToken);
                    },
                    OnRedirectToIdentityProvider = (context) =>
                    {
                        string tenantId;
                        context.Properties.Items.TryGetValue("tenantId", out tenantId);
                        if (tenantId != null)
                        {
                            context.ProtocolMessage.IssuerAddress = context.ProtocolMessage.IssuerAddress.Replace("common", tenantId);
                        }
                        // Overwrite the common if specified
                        return(Task.FromResult(0));
                    },
                    OnTokenValidated = (context) =>
                    {
                        string tenantId;
                        context.Properties.Items.TryGetValue("tenantId", out tenantId);
                        if (tenantId != null)
                        {
                            string userTenantId = context.Ticket.Principal.FindFirst(AzureAdClaimTypes.TenantId)?.Value;
                            if (userTenantId != tenantId)
                            {
                                throw new Exception($"You signed in with wrong tenant, expected: {tenantId} but got {userTenantId}");
                            }
                        }
                        // You would validate whether the organization exists in the system etc.
                        return(Task.FromResult(0));
                    }
                }
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Esempio n. 13
0
        /// <summary>
        /// This function will execute on a timer. For testing purposes, it is setup to execute every 30 seconds.
        /// Typically one would trigger these every 24 hours to ensure subscriptions don't expire.
        /// </summary>
        /// <param name="timer">Timer object containing schedule information.</param>
        /// <param name="binder">Binder object can be used to bind to remote resources such as Azure storage blobs, queues etc.</param>
        /// <param name="cancellationToken">A cancellation token that can be used for long executing functions, in case webjobs is shutting down.</param>
        /// <param name="log">Log object for adding diagnostic logs.</param>
        /// <returns></returns>
        public static async Task ManageSubscriptions(
            [TimerTrigger(Functions.SubscriptionRenewalSchedule, RunOnStartup = true)] TimerInfo timer,
            IBinder binder,
            CancellationToken cancellationToken,
            TextWriter log)
        {
            // Step#1: Obtain App only auth token
            string authority = string.Format(
                CultureInfo.InvariantCulture,
                "https://login.microsoftonline.com/{0}",
                Functions.TenantId);

            ClientCredential clientCredential = new ClientCredential(Functions.ClientSecret);

            var app = new ConfidentialClientApplication(Functions.ClientId, authority,
                                                        RedirectUri, clientCredential, null, new TokenCache());

            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult authenticationResult = null;

            authenticationResult = await app.AcquireTokenForClientAsync(scopes);

            // Step#2: Check if a subscription already exists from a cache. We are using blob storage to cache the subscriptionId.
            // If a subscription doesn't exist in blob store, then we need to create one.
            BlobAttribute blobAttributeRead = new BlobAttribute(Functions.SubscriptionBlobName, FileAccess.Read);
            Stream        steram            = binder.Bind <Stream>(blobAttributeRead);
            StreamBinder  streamBinder      = new StreamBinder();
            string        subscriptionId    = await streamBinder.ReadFromStreamAsync(steram, cancellationToken);

            bool   subscriptionExists = false;
            string subscriptionsUrl   = null;

            if (!string.IsNullOrWhiteSpace(subscriptionId))
            {
                subscriptionsUrl = string.Format(
                    CultureInfo.InvariantCulture,
                    Functions.SubscriptionUrlTemplate,
                    subscriptionId);

                using (HttpRequestMessage message = new HttpRequestMessage(
                           HttpMethod.Get,
                           subscriptionsUrl))
                {
                    message.Headers.Authorization = AuthenticationHeaderValue
                                                    .Parse(authenticationResult.CreateAuthorizationHeader());

                    HttpResponseMessage response = await Functions.Client.SendAsync(message);

                    subscriptionExists = response.IsSuccessStatusCode;
                }
            }

            if (!subscriptionExists)
            {
                Subscription subscription = new Subscription();
                subscription.ChangeType         = "updated,deleted";
                subscription.ClientState        = "mysecret";
                subscription.ExpirationDateTime = DateTime.UtcNow.AddDays(2);
                subscription.NotificationUrl    = Functions.NotificationUrl;
                subscription.Resource           = "Users";

                using (HttpRequestMessage message = new HttpRequestMessage(
                           HttpMethod.Post,
                           Functions.SubscriptionsEntitySetUrl))
                {
                    message.Content = new StringContent(
                        JsonConvert.SerializeObject(subscription),
                        Encoding.UTF8,
                        Functions.ContentTypeApplicationJson);

                    message.Headers.Authorization = AuthenticationHeaderValue
                                                    .Parse(authenticationResult.CreateAuthorizationHeader());

                    HttpResponseMessage response = await Functions.Client.SendAsync(message);

                    response.EnsureSuccessStatusCode();
                    subscription = await response.Content.ReadAsAsync <Subscription>();

                    BlobAttribute blobAttributeWrite = new BlobAttribute(Functions.SubscriptionBlobName, FileAccess.Write);
                    Stream        newState           = binder.Bind <Stream>(blobAttributeWrite);
                    await streamBinder.WriteToStreamAsync(subscription.Id, newState, cancellationToken);

                    log.WriteLine("Created new subscription with id:" + subscription.Id);
                }
            }
            else
            {
                // Step#3: If a subscription already exists in blob store, then we will extend the expiration date by 1 day.
                Dictionary <string, string> update = new Dictionary <string, string>();
                update.Add("expirationDateTime", DateTime.UtcNow.AddDays(1).ToString(Functions.ODataDateTimeFormat));

                using (HttpRequestMessage message = new HttpRequestMessage(
                           Functions.HttpMethodPatch,
                           subscriptionsUrl))
                {
                    message.Content = new StringContent(
                        JsonConvert.SerializeObject(update),
                        Encoding.UTF8,
                        Functions.ContentTypeApplicationJson);

                    message.Headers.Authorization = AuthenticationHeaderValue
                                                    .Parse(authenticationResult.CreateAuthorizationHeader());

                    HttpResponseMessage response = await Functions.Client.SendAsync(message);

                    response.EnsureSuccessStatusCode();

                    log.WriteLine("Updated existing subscription with id:" + subscriptionId);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <remarks>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </remarks>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <Briteplan>(options => options.UseSqlServer(Configuration["Data:ConnectionStrings:BloggingDatabase"]));

            services.AddAuthorization(ConfigureAuthPolicies());

            services.AddSingleton <IAuthorizationHandler, CheckUserRoleHandler>();

            services.AddAuthentication(auth =>
            {
                auth.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
                auth.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddBpJwtBearer(options => Configuration.Bind("TokenOptions", options))
            .AddCookie().AddOpenIdConnect(opts =>
            {
                Configuration.GetSection("Authentication").Bind(opts);

                opts.Events = new OpenIdConnectEvents
                {
                    OnAuthorizationCodeReceived = async ctx =>
                    {
                        var request    = ctx.HttpContext.Request;
                        var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                        var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

                        var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService <IDistributedCache>();
                        var userId           = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                        var cache = new AdalDistributedTokenCache(distributedCache, userId);

                        var authContext = new AuthenticationContext(ctx.Options.Authority, cache);

                        var result = await authContext.AcquireTokenByAuthorizationCodeAsync(ctx.ProtocolMessage.Code,
                                                                                            new Uri(currentUri),
                                                                                            credential,
                                                                                            ctx.Options.Resource);

                        var requiredService = ctx.HttpContext.RequestServices.GetRequiredService <IResourceManager>();
                        var resource        = await requiredService.GetByUsername(result.UserInfo.DisplayableId);
                        if (resource != null)
                        {
                            var claims = new List <Claim>
                            {
                                new Claim(YstervarkClaimNames.ResourceName, resource.ResourceName),
                                new Claim(YstervarkClaimNames.ResourceId, resource.ResourceId.ToString()),
                                new Claim(YstervarkClaimNames.TenantId, resource.TenantId.ToString()),
                                new Claim(JwtRegisteredClaimNames.Email, resource.Emailaddress),
                            };
                            claims.AddRange(resource.ResourceRole.Select(roleModel =>
                                                                         new Claim(ClaimsIdentity.DefaultRoleClaimType, roleModel.Role.RoleName)));
                            ctx.Principal.AddIdentity(new ClaimsIdentity(claims));
                        }
                        else
                        {
                            ctx.Fail(new UnauthorizedAccessException());
                            return;
                        }

                        ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    }
                };
            });

            services.AddMvc().AddJsonOptions(j =>
            {
                j.SerializerSettings.ContractResolver  = new DefaultContractResolver();
                j.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                             new Info
                {
                    Title   = "Ystervark",
                    Version = "v1",
                    Contact = new Contact
                    {
                        Email = "*****@*****.**",
                        Name  = "Richard Bailey",
                        Url   = "https://github.com/Programm3r"
                    }
                });
            });

            services.AddSignalR();
        }
        // GET: /<controller>/
        public async Task <IActionResult> Index()
        {
            AuthenticationResult result   = null;
            List <TodoItem>      itemList = new List <TodoItem>();

            try
            {
                // Because we signed-in already in the WebApp, the userObjectId is know
                string userObjectID = (User?.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
                AuthenticationContext authContext = null;

                if (userObjectID != null)
                {
                    // Using ADAL.Net, get a bearer token to access the TodoListService
                    authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
                    ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
                    result = await authContext.AcquireTokenSilentAsync(AzureAdOptions.Settings.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
                }

                // Retrieve the user's To Do List.
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, AzureAdOptions.Settings.TodoListBaseAddress + "/api/todolist");
                Logger.LogInformation("API URL: {0}", request.RequestUri.ToString());
                if (result != null)
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                }
                HttpResponseMessage response = await client.SendAsync(request);

                // Return the To Do List in the view.
                if (response.IsSuccessStatusCode)
                {
                    List <Dictionary <String, String> > responseElements = new List <Dictionary <String, String> >();
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    String responseString           = await response.Content.ReadAsStringAsync();

                    responseElements = JsonConvert.DeserializeObject <List <Dictionary <String, String> > >(responseString, settings);
                    foreach (Dictionary <String, String> responseElement in responseElements)
                    {
                        TodoItem newItem = new TodoItem();
                        newItem.Title = responseElement["title"];
                        newItem.Owner = responseElement["owner"];
                        itemList.Add(newItem);
                    }

                    return(View(itemList));
                }

                //
                // If the call failed with access denied, then drop the current access token from the cache,
                //     and show the user an error indicating they might need to sign-in again.
                //
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    return(ProcessUnauthorized(itemList, authContext));
                }
            }
            catch (Exception)
            {
                if (HttpContext.Request.Query["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    return(new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme));
                }
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                TodoItem newItem = new TodoItem();
                newItem.Title = "(Sign-in required to view to do list.)";
                itemList.Add(newItem);
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View(itemList));
            }
            //
            // If the call failed for any other reason, show the user an error.
            //
            return(View("Error"));
        }
Esempio n. 16
0
        //
        // GET: /UserProfile/
        public async Task <ActionResult> Index()
        {
            //
            // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API.
            //
            UserProfile          profile;
            AuthenticationResult result = null;

            try
            {
                string tenantId     = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
                ClientCredential      credential  = new ClientCredential(clientId, appKey);
                result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                //
                // Call the Graph API and retrieve the user's profile.
                //
                string requestUrl = String.Format(
                    CultureInfo.InvariantCulture,
                    graphUserUrl,
                    HttpUtility.UrlEncode(tenantId));
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                //
                // Return the user's profile in the view.
                //
                if (response.IsSuccessStatusCode)
                {
                    string responseString = await response.Content.ReadAsStringAsync();

                    profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                }
                else
                {
                    //
                    // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                    //
                    var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == graphResourceId);
                    foreach (TokenCacheItem tci in todoTokens)
                    {
                        authContext.TokenCache.DeleteItem(tci);
                    }

                    profile              = new UserProfile();
                    profile.DisplayName  = " ";
                    profile.GivenName    = " ";
                    profile.Surname      = " ";
                    ViewBag.ErrorMessage = "UnexpectedError";
                }

                return(View(profile));
            }
            catch (AdalException ee)
            {
                //
                // If the user doesn't have an access token, they need to re-authorize.
                //

                //
                // If refresh is set to true, the user has clicked the link to be authorized again.
                //
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(
                        new AuthenticationProperties(),
                        OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                profile              = new UserProfile();
                profile.DisplayName  = " ";
                profile.GivenName    = " ";
                profile.Surname      = " ";
                ViewBag.ErrorMessage = "AuthorizationRequired";

                return(View(profile));
            }
        }
Esempio n. 17
0
 public AzureKeyVaultConfigStore(Uri vaultUri, string azureAadClientId, string azureAadClientSecret)
 {
     _credential  = new ClientCredential(azureAadClientId, azureAadClientSecret);
     _vaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken), GetHttpClient());
     _vaultUri    = vaultUri.ToString();
 }
        public static FileProcessedTracker Run([BlobTrigger("snotel-csv-westus-v1/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob, string name, TraceWriter log)
        {
            log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");

            log.Info($"Double Checking if {name} already exists.");
            var exists = AzureUtilities.CheckIfFileProcessedRowExistsInTableStorage(Constants.SnotelTrackerTable, Constants.SnotelTrackerPartitionKey, name, log);

            if (exists)
            {
                log.Info($"{name} Already exists in double check, skipping");
                return(null);
            }
            //1. Remove header from stream
            var          s         = new MemoryStream();
            StreamWriter csvWriter = new StreamWriter(s, Encoding.UTF8);
            bool         firstLine = true;

            using (StreamReader sr = new StreamReader(myBlob))
            {
                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith("#"))
                    {
                        //throw out this header
                        continue;
                    }
                    else
                    {
                        //Dates in the file are local times; need to change them to UTC which is +8
                        //These dates don't adjust for daylight savings time
                        var splitLine = line.Split(',');
                        if (firstLine == false && splitLine.Length > 1)
                        {
                            var localTimeOfForecast = DateTime.Parse(splitLine[0]);
                            var utcTimeOfForecast   = localTimeOfForecast.AddHours(+8);
                            splitLine[0] = utcTimeOfForecast.ToString("yyyyMMdd HH:00");
                            line         = String.Join(",", splitLine);
                        }
                        firstLine = false;
                        csvWriter.WriteLine(line);
                    }
                }
            }
            csvWriter.Flush();
            s.Position = 0;

            //refactoring the below code to a shared method can cause an .net issue
            //related to binding redirect to arise; leave this here for now.  See AzureUtilities.cs
            //for more info
            log.Info($"Attempting to sign in to ad for datalake upload");
            var adlsAccountName = CloudConfigurationManager.GetSetting("ADLSAccountName");

            //auth secrets
            var domain           = CloudConfigurationManager.GetSetting("Domain");
            var webApp_clientId  = CloudConfigurationManager.GetSetting("WebAppClientId");
            var clientSecret     = CloudConfigurationManager.GetSetting("ClientSecret");
            var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
            var creds            = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;

            // Create client objects and set the subscription ID
            var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);

            //string subId = CloudConfigurationManager.GetSetting("SubscriptionId");

            try
            {
                adlsFileSystemClient.FileSystem.Create(adlsAccountName, "/snotel-csv-westus-v1/" + name, s, overwrite: true);
                log.Info($"Uploaded csv stream: {name}");
            }
            catch (Exception e)
            {
                log.Info($"Upload failed: {e.Message}");
            }
            var      splitFileName = name.Split('.');
            DateTime date          = DateTime.ParseExact(splitFileName[0], "yyyyMMdd", null).AddHours(int.Parse(splitFileName[1]));

            return(new FileProcessedTracker {
                ForecastDate = date, PartitionKey = "snotel-csv-westus-v1", RowKey = name, Url = "unknown"
            });
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                //AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                //LoginPath = new PathString("/Account/Login"),
                //Provider = new CookieAuthenticationProvider
                //{
                //    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                //        validateInterval: TimeSpan.FromMinutes(30),
                //        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                //}
                SlidingExpiration = true,
                ExpireTimeSpan    = TimeSpan.FromMinutes(480)
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = ConfigurationManager.AppSettings["Ida:ClientId"],
                Authority             = ConfigurationManager.AppSettings["Ida:AadInstance"] + ConfigurationManager.AppSettings["Ida:Tenant"],
                RedirectUri           = ConfigurationManager.AppSettings["Ida:RedirectUri"],
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["Ida:RedirectUri"],
                Scope        = OpenIdConnectScope.OpenIdProfile,
                ResponseType = OpenIdConnectResponseType.IdToken,
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    SaveSigninToken = true,
                    ValidateIssuer  = false
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async context =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                        var authContext             = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(ConfigHelper.Authority, new ADALTokenCache(Util.GetSignedInUsersObjectIdFromClaims()));

                        // This method exchanges the auth code for an access token and refresh token
                        // Note that this also stores both tokens in the token cache that is configured
                        // in the AuthenticationContext, where they will be automatically retrieved or
                        // refreshed by calling AcquireTokenSilentAsync()
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId).Result;

                        //return System.Threading.Tasks.Task.FromResult(0);
                    },
                    //SecurityTokenValidated = async context =>
                    //{
                    //    var token = new JwtSecurityToken(context.ProtocolMessage.IdToken);
                    //    var claims = new ClaimsIdentity(token.Claims);
                    //    claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, claims.FindFirst("name")?.Value));
                    //    claims.AddClaim(new Claim(Globals.ObjectIdClaimType, claims.FindFirst("oid")?.Value));
                    //    claims.AddClaim(new Claim(ClaimTypes.Email, (claims.FindFirst("upn") ?? claims.FindFirst("email"))?.Value));
                    //    claims.AddClaim(new Claim("access_token", context.ProtocolMessage.IdToken));
                    //    //claims.BootstrapContext = new BootstrapContext(context.ProtocolMessage.IdToken);
                    //    //var claims = context.Request.User.Identity as ClaimsIdentity;
                    //    var groups = await UserInfoHelper.GetAllGroups(claims);
                    //},
                    AuthenticationFailed = (context) =>
                    {
                        if (context.Exception.Message.StartsWith("OICE_20004") || context.Exception.Message.Contains("IDX10311"))
                        {
                            context.SkipToNextMiddleware();
                            return(System.Threading.Tasks.Task.FromResult(0));
                        }
                        return(System.Threading.Tasks.Task.FromResult(0));
                    }
                }
            });

            app.Use(typeof(UserGroupCachingMiddleware));

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            //// Enables the application to remember the second login verification factor such as phone or email.
            //// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            //// This is similar to the RememberMe option when you log in.
            //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //    app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //    {
            //      ClientId = "000000000000.apps.googleusercontent.com",
            //      ClientSecret = "00000000000"
            //    });
        }
        public static FileProcessedTracker Run([QueueTrigger("downloadandunpacksnodas", Connection = "AzureWebJobsStorage")] FileReadyToDownloadQueueMessage myQueueItem,
                                               TraceWriter log)
        {
            log.Info($"C# Queue trigger function processed snodas date: {myQueueItem.FileDate}");

            string partitionName = myQueueItem.Filetype;

            var urlToDownload = myQueueItem.Url;

            log.Info($"Downloading Url {urlToDownload}");

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(urlToDownload);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("anonymous", "");
            List <string>  listOfUnpackedFiles = null;
            FtpWebResponse response            = (FtpWebResponse)request.GetResponse();

            log.Info($"File {urlToDownload} downloaded");
            Stream responseStream = response.GetResponseStream();

            listOfUnpackedFiles = SnodasUtilities.UnpackSnodasStream(responseStream);
            log.Info($"File {urlToDownload} unpacked");

            //fix the bard codes in the hdr files
            foreach (var f in listOfUnpackedFiles.Where(s => s.ToLower().Contains(".hdr")))
            {
                SnodasUtilities.RemoveBardCodesFromHdr(f);
            }

            log.Info($"Attempting to sign in to ad for datalake upload");
            var adlsAccountName = CloudConfigurationManager.GetSetting("ADLSAccountName");

            //auth secrets
            var domain           = CloudConfigurationManager.GetSetting("Domain");
            var webApp_clientId  = CloudConfigurationManager.GetSetting("WebAppClientId");
            var clientSecret     = CloudConfigurationManager.GetSetting("ClientSecret");
            var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
            var creds            = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;

            // Create client objects and set the subscription ID
            var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);

            log.Info($"Attempting to upload unpacked files to adls");
#if DEBUG
//            listOfUnpackedFiles = listOfUnpackedFiles.Where(f => f.Contains(".Hdr")).Take(1).ToList();
#endif
            foreach (var file in listOfUnpackedFiles)
            {
                try
                {
                    adlsFileSystemClient.FileSystem.UploadFile(adlsAccountName, file, "/snodas-dat-us-v1/" + file.Split('\\').Last(), uploadAsBinary: true, overwrite: true);
                    log.Info($"Uploaded file: {file}");
                }
                catch (Exception e)
                {
                    log.Error($"Upload failed: {e.Message}");
                }
            }

            //1: Get values for lat/lon
            var locations = AzureUtilities.DownloadLocations(log);
#if DEBUG
            var executingAssemblyFile = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
            var executingDirectory    = Path.GetDirectoryName(executingAssemblyFile);

            if (string.IsNullOrEmpty(executingDirectory))
            {
                throw new InvalidOperationException("cannot get executing directory");
            }
            executingDirectory = Directory.GetParent(executingDirectory).FullName;

            var gdalPath = Path.Combine(executingDirectory, "gdal");
            log.Info($"Have gdal path {gdalPath}");
#endif
            log.Info($"Configuring gdal");
            GdalConfiguration.ConfigureGdal();
            var results = SnodasUtilities.GetValuesForCoordinates(locations, listOfUnpackedFiles.Where(f => f.Contains(".Hdr")).ToList());
            log.Info($"Have {results.Count} results for coordinates.");
            DateTime fileDate;
            string   fileName;
            using (MemoryStream s = new MemoryStream())
                using (StreamWriter csvWriter = new StreamWriter(s, Encoding.UTF8))
                {
                    csvWriter.WriteLine(SnodasRow.GetHeader);
                    foreach (var row in results)
                    {
                        csvWriter.WriteLine(row.ToString());
                    }
                    csvWriter.Flush();
                    s.Position = 0;

                    fileDate = results[0].Date;
                    fileName = fileDate.ToString("yyyyMMdd") + "Snodas.csv";
                    try
                    {
                        adlsFileSystemClient.FileSystem.Create(adlsAccountName, "/snodas-csv-westus-v1/" + fileName, s, overwrite: true);
                        log.Info($"Uploaded csv stream: {fileName}");
                    }
                    catch (Exception e)
                    {
                        log.Info($"Upload failed: {e.Message}");
                    }
                }

            log.Info($"Removing unpacked files");
            foreach (var f in listOfUnpackedFiles)
            {
                //delete local temp file
                File.Delete(f);
            }
            return(new FileProcessedTracker {
                ForecastDate = fileDate, PartitionKey = "snodas-westus-v1", RowKey = fileName, Url = "unknown"
            });
        }
    public async Task<ActionResult> Calendar()
    {
      AuthenticationContext authContext = new AuthenticationContext(authority);

      ClientCredential credential = new ClientCredential(appId, appSecret);
      AuthenticationResult authResult = null;
      try
      {
        authResult = await authContext.AcquireTokenSilentAsync(scopes, credential, UserIdentifier.AnyUser);
      }
      catch (AdalException ex)
      {
        TempData["message"] = "Please sign in to continue";
        return Redirect("/");
      }

      var client = new Outlook();
      client.anchorMailbox = GetUserEmail(authContext, appId);
      ViewBag.UserName = client.anchorMailbox;

      DateTime viewStart = DateTime.Now.ToUniversalTime();
      DateTime viewEnd = viewStart.AddHours(3);
      var result = await client.GetCalendarView(authResult.Token, client.anchorMailbox, viewStart, viewEnd);

      return View(result);
    }
        /// <summary>
        /// Deploy the template from the template file template.json. Write the keys returned by the deployment into files
        /// </summary>
        public static void DeployTemplate()
        {
            spin.setMessage("Deploying Template...");
            spin.Start();
            // string templatePath = "https://" + acccountStorageName + ".blob.core.windows.net/templates/templateIotHub.json";
            // string paramPath = "https://" + acccountStorageName + ".blob.core.windows.net/templates/parameters.json";
            // var deployment = azure.Deployments.Define("Deployment_01")
            //                     .WithExistingResourceGroup(resourceGroup)
            //                     .WithTemplateLink(templatePath, "1.0.0.0")
            //                     .WithParametersLink(paramPath, "1.0.0.0")
            //                     .WithMode(DeploymentMode.Incremental)
            //                     .Create();

            // IDeployment toto = await azure.Deployments.GetByNameAsync("Deployment_01");
            Microsoft.Azure.Management.ResourceManager.ResourceManagementClient client;

            var authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantId));

            var credential             = new ClientCredential(applicationId, password);
            AuthenticationResult token = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential).Result;


            if (token == null)
            {
                Console.WriteLine("Failed to obtain the token");
                return;
            }

            var creds = new TokenCredentials(token.AccessToken);

            client = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(creds);
            client.SubscriptionId = subscriptionId;


            var createResponse = client.Deployments.CreateOrUpdate(rgName, deploymentName, new Microsoft.Azure.Management.ResourceManager.Models.Deployment()
            {
                Properties = new DeploymentProperties
                {
                    Mode         = Microsoft.Azure.Management.ResourceManager.Models.DeploymentMode.Incremental,
                    TemplateLink = new Microsoft.Azure.Management.ResourceManager.Models.TemplateLink
                    {
                        Uri = "https://" + accountStorageName + ".blob.core.windows.net/templates/template.json"
                    },
                    ParametersLink = new Microsoft.Azure.Management.ResourceManager.Models.ParametersLink
                    {
                        Uri = "https://" + accountStorageName + ".blob.core.windows.net/templates/parameters.json"
                    }
                }
            });

            spin.Stop();
            string state = createResponse.Properties.ProvisioningState;

            Console.WriteLine("Deployment state: {0}", state);

            if (state != "Succeeded")
            {
                Console.WriteLine("Failed to deploy the template");
            }
            Console.WriteLine(createResponse.Properties.Outputs);
            WriteKeysIntoFiles(createResponse.Properties.Outputs);
            Console.WriteLine("Done");
            //Console.ReadLine();
        }
Esempio n. 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataAccessProxy"/> class.
 /// </summary>
 /// <param name="credential">The client credential used for consuming the data access functionalities.</param>
 public DataAccessProxy(ClientCredential credential)
 {
     this.credential = credential;
 }
Esempio n. 24
0
        public static async System.Threading.Tasks.Task <IActionResult> RunAsync([BlobTrigger("witdatauploadblob/{name}", Connection = "AzureStorageBlobConnectionString")] Stream myBlob, string name, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");


            string tenantId          = Environment.GetEnvironmentVariable($"tenantId");
            string applicationId     = Environment.GetEnvironmentVariable($"applicationId");
            string authenticationKey = Environment.GetEnvironmentVariable($"authenticationKey");
            string subscriptionId    = Environment.GetEnvironmentVariable($"subscriptionId");
            string resourceGroup     = Environment.GetEnvironmentVariable($"resourceGroup");
            string factoryName       = Environment.GetEnvironmentVariable($"factoryName");
            string pipelineName      = Environment.GetEnvironmentVariable($"pipelineName");

            //Check body for values
            if (
                tenantId == null ||
                applicationId == null ||
                authenticationKey == null ||
                subscriptionId == null ||
                factoryName == null ||
                pipelineName == null
                )
            {
                return(new BadRequestObjectResult("Invalid request body, value missing."));
            }

            //Create a data factory management client
            var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
            ClientCredential         cc     = new ClientCredential(applicationId, authenticationKey);
            AuthenticationResult     result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result;
            ServiceClientCredentials cred   = new TokenCredentials(result.AccessToken);
            var client = new DataFactoryManagementClient(cred)
            {
                SubscriptionId = subscriptionId
            };

            //Run pipeline
            CreateRunResponse runResponse;
            PipelineRun       pipelineRun;

            log.LogInformation("Called pipeline");

            runResponse = client.Pipelines.CreateRunWithHttpMessagesAsync(
                resourceGroup, factoryName, pipelineName).Result.Body;

            log.LogInformation("Pipeline run ID: " + runResponse.RunId);

            //Wait and check for pipeline result
            log.LogInformation("Checking pipeline run status...");
            while (true)
            {
                pipelineRun = client.PipelineRuns.Get(
                    resourceGroup, factoryName, runResponse.RunId);

                log.LogInformation("Status: " + pipelineRun.Status);

                if (pipelineRun.Status == "InProgress" || pipelineRun.Status == "Queued")
                {
                    System.Threading.Thread.Sleep(15000);
                }
                else
                {
                    break;
                }
            }

            //Final return detail
            string  outputString = "{ \"PipelineName\": \"" + pipelineName + "\", \"RunIdUsed\": \"" + pipelineRun.RunId + "\", \"Status\": \"" + pipelineRun.Status + "\" }";
            JObject outputJson   = JObject.Parse(outputString);

            return(new OkObjectResult(outputJson));
        }
        public async Task <StatusCodeResult> PostAsync()
        {
            string serviceUrl = "https://org5690cc64.crm11.dynamics.com";
            string clientId   = "e8ace036-8aa5-4e66-89fc-ec9cc3afbe57";
            string secret     = "_b_6SB18VX2~IiM0jTjX7xp.dX-joVdjGv";

            AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/eaec5a17-a66c-43a4-881c-edfc212aafa6");
            ClientCredential      credential  = new ClientCredential(clientId, secret);

            AuthenticationResult result = await authContext.AcquireTokenAsync(serviceUrl, credential);

            var authHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://org5690cc64.crm11.dynamics.com/api/data/v9.1/");
                client.DefaultRequestHeaders.Authorization = authHeader;

                var response = client.GetAsync("crc66_storeses").Result;

                if (response.IsSuccessStatusCode)
                {
                    var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);

                    var json = await response.Content.ReadAsStringAsync();

                    var stores = JsonSerializer.Deserialize <ODataResponse <CDSStore> >(json).Value.Select((a, index) =>
                    {
                        Store store = _repository.Get(a.ID);
                        if (store == null)
                        {
                            store = new Store
                            {
                                StoreID = a.ID
                            };
                        }

                        store.Name     = a.Name;
                        store.Location = geometryFactory.CreatePoint(new Coordinate(Convert.ToDouble(a.Longitude), Convert.ToDouble(a.Latitude)));
                        store.Address  = new StoreAddress
                        {
                            LineOne   = a.AddressLine1,
                            LineTwo   = a.AddressLine2,
                            LineThree = a.AddressLine3,
                            City      = a.AddressCity,
                            Postcode  = a.AddressPostcode
                        };

                        store.OperatingHours = new StoreOperatingDays
                        {
                            Monday = new StoreOperatingHours {
                                Open = a.OperatingHourMondayOpen, Closed = a.OperatingHourMondayClosed
                            },
                            Tuesday = new StoreOperatingHours {
                                Open = a.OperatingHourTuesdayOpen, Closed = a.OperatingHourTuesdayClosed
                            },
                            Wednesday = new StoreOperatingHours {
                                Open = a.OperatingHourWednesdayOpen, Closed = a.OperatingHourWednesdayClosed
                            },
                            Thursday = new StoreOperatingHours {
                                Open = a.OperatingHourThursdayOpen, Closed = a.OperatingHourThursdayClosed
                            },
                            Friday = new StoreOperatingHours {
                                Open = a.OperatingHourFridayOpen, Closed = a.OperatingHourFridayClosed
                            },
                            Saturday = new StoreOperatingHours {
                                Open = a.OperatingHourSaturdayOpen, Closed = a.OperatingHourSaturdayClosed
                            },
                            Sunday = new StoreOperatingHours {
                                Open = a.OperatingHourSundayOpen, Closed = a.OperatingHourSundayClosed
                            }
                        };

                        return(store);
                    });

                    _repository.Save(stores);
                }
            }

            return(Ok());
        }
Esempio n. 26
0
 public LocalStorageAccessProxy(ClientCredential credential)
     : base(credential)
 {
 }
Esempio n. 27
0
        public static async Task <UserProfile> CallGraphAPIOnBehalfOfUser()
        {
            UserProfile          profile     = null;
            string               accessToken = null;
            AuthenticationResult result      = null;

            //
            // Use ADAL to get a token On Behalf Of the current user.  To do this we will need:
            //      The Resource ID of the service we want to call.
            //      The current user's access token, from the current request's authorization header.
            //      The credentials of this application.
            //      The username (UPN or email) of the user calling the API
            //
            ClientCredential clientCred = new ClientCredential(clientId, appKey);
            var    bootstrapContext     = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
            string userName             = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null?ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;

            string        userAccessToken = bootstrapContext.Token;
            UserAssertion userAssertion   = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
            string userId    = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            AuthenticationContext authContext = new AuthenticationContext(authority, new DbTokenCache(userId));

            // In the case of a transient error, retry once after 1 second, then abandon.
            // Retrying is optional.  It may be better, for your application, to return an error immediately to the user and have the user initiate the retry.
            bool retry      = false;
            int  retryCount = 0;

            do
            {
                retry = false;
                try
                {
                    result = await authContext.AcquireTokenAsync(graphResourceId, clientCred, userAssertion);

                    accessToken = result.AccessToken;
                }
                catch (AdalException ex)
                {
                    if (ex.ErrorCode == SERVICE_UNAVAILABLE)
                    {
                        // Transient error, OK to retry.
                        retry = true;
                        retryCount++;
                        Thread.Sleep(1000);
                    }
                }
            } while ((retry == true) && (retryCount < 2));

            if (accessToken == null)
            {
                // An unexpected error occurred.
                return(null);
            }

            //
            // Call the Graph API and retrieve the user's profile.
            //
            string requestUrl = String.Format(
                CultureInfo.InvariantCulture,
                graphUserUrl,
                HttpUtility.UrlEncode(tenant));
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            //
            // Return the user's profile.
            //
            if (response.IsSuccessStatusCode)
            {
                string responseString = await response.Content.ReadAsStringAsync();

                profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                return(profile);
            }

            // An unexpected error occurred calling the Graph API.  Return a null profile.
            return(null);
        }
 public Task <AuthenticationResult> AcquireTokenAsync(string resource, ClientCredential clientCredential)
 {
     return(_authenticationContext.AcquireTokenAsync(resource, clientCredential));
 }
        public async Task <ActionResult> Index(string item)
        {
            if (ModelState.IsValid)
            {
                //
                // Retrieve the user's tenantID and access token since they are parameters used to call the To Do service.
                //
                AuthenticationResult result   = null;
                List <TodoItem>      itemList = new List <TodoItem>();

                try
                {
                    string userObjectID = (User?.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
                    AuthenticationContext authContext = null;

                    if (authContext != null)
                    {
                        authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
                        ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
                        result = await authContext.AcquireTokenSilentAsync(AzureAdOptions.Settings.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
                    }

                    // Forms encode todo item, to POST to the todo list web api.
                    HttpContent content = new StringContent(JsonConvert.SerializeObject(new { Title = item }), System.Text.Encoding.UTF8, "application/json");

                    //
                    // Add the item to user's To Do List.
                    //
                    HttpClient         client  = new HttpClient();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, AzureAdOptions.Settings.TodoListBaseAddress + "/api/todolist");
                    if (result != null)
                    {
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    }
                    request.Content = content;
                    HttpResponseMessage response = await client.SendAsync(request);

                    //
                    // Return the To Do List in the view.
                    //
                    if (response.IsSuccessStatusCode)
                    {
                        return(RedirectToAction("Index"));
                    }

                    //
                    // If the call failed with access denied, then drop the current access token from the cache,
                    //     and show the user an error indicating they might need to sign-in again.
                    //
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(ProcessUnauthorized(itemList, authContext));
                    }
                }
                catch (Exception)
                {
                    //
                    // The user needs to re-authorize.  Show them a message to that effect.
                    //
                    TodoItem newItem = new TodoItem();
                    newItem.Title = "(No items in list)";
                    itemList.Add(newItem);
                    ViewBag.ErrorMessage = "AuthorizationRequired";
                    return(View(itemList));
                }
                //
                // If the call failed for any other reason, show the user an error.
                //
                return(View("Error"));
            }
            return(View("Error"));
        }
        //
        // GET: /UserProfile/
        public async Task <ActionResult> Index(string authError)
        {
            UserProfile           profile     = null;
            AuthenticationContext authContext = null;
            AuthenticationResult  result      = null;
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;

            try
            {
                ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey);
                authContext = new AuthenticationContext(Startup.Authority, new TokenDbCache(userObjectID));

                if (authError != null)
                {
                    Uri    redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");
                    string state       = GenerateState(userObjectID, Request.Url.ToString());
                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(Startup.graphResourceId, Startup.clientId, redirectUri, UserIdentifier.AnyUser, state == null ? null : "&state=" + state);

                    profile              = new UserProfile();
                    profile.DisplayName  = " ";
                    profile.GivenName    = " ";
                    profile.Surname      = " ";
                    ViewBag.ErrorMessage = "UnexpectedError";
                    return(View(profile));
                }

                result = authContext.AcquireTokenSilent(Startup.graphResourceId, credential, UserIdentifier.AnyUser);
            }
            catch (AdalException e)
            {
                if (e.ErrorCode == "failed_to_acquire_token_silently")
                {
                    // The user needs to re-authorize.  Show them a message to that effect.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.

                    profile              = new UserProfile();
                    profile.DisplayName  = " ";
                    profile.GivenName    = " ";
                    profile.Surname      = " ";
                    ViewBag.ErrorMessage = "AuthorizationRequired";
                    authContext          = new AuthenticationContext(Startup.Authority);
                    Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");

                    string state = GenerateState(userObjectID, Request.Url.ToString());

                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(Startup.graphResourceId, Startup.clientId, redirectUri, UserIdentifier.AnyUser, state == null ? null : "&state=" + state);

                    return(View(profile));
                }

                ViewBag.ErrorMessage = "Error while Acquiring Token from Cache.";
                return(View("Error"));
            }

            try
            {
                //
                // Call the Graph API and retrieve the user's profile.
                //
                string requestUrl = String.Format(
                    CultureInfo.InvariantCulture,
                    Startup.graphUserUrl,
                    HttpUtility.UrlEncode(result.TenantId));
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                //
                // Return the user's profile in the view.
                //
                if (response.IsSuccessStatusCode)
                {
                    string responseString = await response.Content.ReadAsStringAsync();

                    profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                    return(View(profile));
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    //
                    // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                    //
                    authContext.TokenCache.Clear();

                    Uri    redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth");
                    string state       = GenerateState(userObjectID, Request.Url.ToString());
                    ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(Startup.graphResourceId, Startup.clientId, redirectUri, UserIdentifier.AnyUser, state == null ? null : "&state=" + state);

                    profile              = new UserProfile();
                    profile.DisplayName  = " ";
                    profile.GivenName    = " ";
                    profile.Surname      = " ";
                    ViewBag.ErrorMessage = "UnexpectedError";
                    return(View(profile));
                }

                ViewBag.ErrorMessage = "Error Calling Graph API.";
                return(View("Error"));
            }
            catch
            {
                ViewBag.ErrorMessage = "Error Calling Graph API.";
                return(View("Error"));
            }
        }
        static async Task <Tuple <int, HttpResponseMessage, string> > GetDynamicsHttpClientNew(IConfiguration configuration, String model, String endPointName)
        {
            Console.WriteLine(DateTime.Now + " In GetDynamicsHttpClientNew");
            var builder = new ConfigurationBuilder()
                          .AddEnvironmentVariables()
                          .AddUserSecrets <Program>(); // must also define a project guid for secrets in the .cspro – add tag <UserSecretsId> containing a guid
            var Configuration = builder.Build();

            Console.WriteLine(DateTime.Now + " Build Configuration");

            string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; // Dynamics ODATA endpoint
            string dynamicsJobName  = endPointName;                        // Configuration["DYNAMICS_JOB_NAME"]; // Dynamics Job Name

            if (string.IsNullOrEmpty(dynamicsOdataUri))
            {
                throw new Exception("Configuration setting DYNAMICS_ODATA_URI is blank.");
            }

            // Cloud - x.dynamics.com
            string aadTenantId              = Configuration["DYNAMICS_AAD_TENANT_ID"];      // Cloud AAD Tenant ID
            string serverAppIdUri           = Configuration["DYNAMICS_SERVER_APP_ID_URI"];  // Cloud Server App ID URI
            string appRegistrationClientKey = Configuration["DYNAMICS_APP_REG_CLIENT_KEY"]; // Cloud App Registration Client Key
            string appRegistrationClientId  = Configuration["DYNAMICS_APP_REG_CLIENT_ID"];  // Cloud App Registration Client Id

            // One Premise ADFS (2016)
            string adfsOauth2Uri            = Configuration["ADFS_OAUTH2_URI"];              // ADFS OAUTH2 URI - usually /adfs/oauth2/token on STS
            string applicationGroupResource = Configuration["DYNAMICS_APP_GROUP_RESOURCE"];  // ADFS 2016 Application Group resource (URI)
            string applicationGroupClientId = Configuration["DYNAMICS_APP_GROUP_CLIENT_ID"]; // ADFS 2016 Application Group Client ID
            string applicationGroupSecret   = Configuration["DYNAMICS_APP_GROUP_SECRET"];    // ADFS 2016 Application Group Secret
            string serviceAccountUsername   = Configuration["DYNAMICS_USERNAME"];            // Service account username
            string serviceAccountPassword   = Configuration["DYNAMICS_PASSWORD"];            // Service account password

            // API Gateway to NTLM user.  This is used in v8 environments.  Note that the SSG Username and password are not the same as the NTLM user.
            string ssgUsername = Configuration["SSG_USERNAME"];  // BASIC authentication username
            string ssgPassword = Configuration["SSG_PASSWORD"];  // BASIC authentication password

            Console.WriteLine(DateTime.Now + " Variables have been set");

            ServiceClientCredentials serviceClientCredentials = null;

            if (!string.IsNullOrEmpty(appRegistrationClientId) && !string.IsNullOrEmpty(appRegistrationClientKey) && !string.IsNullOrEmpty(serverAppIdUri) && !string.IsNullOrEmpty(aadTenantId))
            // Cloud authentication - using an App Registration's client ID, client key.  Add the App Registration to Dynamics as an Application User.
            {
                Console.WriteLine(DateTime.Now + " Trying Cloud Authentication");
                var authenticationContext = new AuthenticationContext(
                    "https://login.windows.net/" + aadTenantId);
                ClientCredential clientCredential = new ClientCredential(appRegistrationClientId, appRegistrationClientKey);
                var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential);
                task.Wait();
                var    authenticationResult = task.Result;
                string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                serviceClientCredentials = new TokenCredentials(token);
            }
            if (!string.IsNullOrEmpty(adfsOauth2Uri) &&
                !string.IsNullOrEmpty(applicationGroupResource) &&
                !string.IsNullOrEmpty(applicationGroupClientId) &&
                !string.IsNullOrEmpty(applicationGroupSecret) &&
                !string.IsNullOrEmpty(serviceAccountUsername) &&
                !string.IsNullOrEmpty(serviceAccountPassword))
            // ADFS 2016 authentication - using an Application Group Client ID and Secret, plus service account credentials.
            {
                Console.WriteLine(DateTime.Now + " Trying ADFS Authentication");
                // create a new HTTP client that is just used to get a token.
                var stsClient = new HttpClient();

                //stsClient.DefaultRequestHeaders.Add("x-client-SKU", "PCL.CoreCLR");
                //stsClient.DefaultRequestHeaders.Add("x-client-Ver", "5.1.0.0");
                //stsClient.DefaultRequestHeaders.Add("x-ms-PKeyAuth", "1.0");

                stsClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString());
                stsClient.DefaultRequestHeaders.Add("return-client-request-id", "true");
                stsClient.DefaultRequestHeaders.Add("Accept", "application/json");

                // Construct the body of the request
                var pairs = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("resource", applicationGroupResource),
                    new KeyValuePair <string, string>("client_id", applicationGroupClientId),
                    new KeyValuePair <string, string>("client_secret", applicationGroupSecret),
                    new KeyValuePair <string, string>("username", serviceAccountUsername),
                    new KeyValuePair <string, string>("password", serviceAccountPassword),
                    new KeyValuePair <string, string>("scope", "openid"),
                    new KeyValuePair <string, string>("response_mode", "form_post"),
                    new KeyValuePair <string, string>("grant_type", "password")
                };

                Console.WriteLine(DateTime.Now + " Set ADFS variables and headers");

                // This will also set the content type of the request
                var content = new FormUrlEncodedContent(pairs);
                Console.WriteLine(DateTime.Now + " content: " + content);
                // send the request to the ADFS server
                Console.WriteLine(DateTime.Now + " About to send request to ADFS");
                var _httpResponse    = stsClient.PostAsync(adfsOauth2Uri, content).GetAwaiter().GetResult();
                var _responseContent = _httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                // response should be in JSON format.
                try
                {
                    Dictionary <string, string> result = JsonConvert.DeserializeObject <Dictionary <string, string> >(_responseContent);
                    string token = result["access_token"];
                    Console.WriteLine(DateTime.Now + " Got a token");
                    // set the bearer token.
                    serviceClientCredentials = new TokenCredentials(token);


                    // Code to perform Scheduled task
                    var client = new HttpClient();
                    client.DefaultRequestHeaders.Add("x-client-SKU", "PCL.CoreCLR");
                    client.DefaultRequestHeaders.Add("x-client-Ver", "5.1.0.0");
                    client.DefaultRequestHeaders.Add("x-ms-PKeyAuth", "1.0");
                    client.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString());
                    client.DefaultRequestHeaders.Add("return-client-request-id", "true");
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    client = new HttpClient();
                    var Authorization = $"Bearer {token}";
                    client.DefaultRequestHeaders.Add("Authorization", Authorization);
                    client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                    client.DefaultRequestHeaders.Add("OData-Version", "4.0");
                    client.DefaultRequestHeaders.Add("Accept", "application/json");
                    //client.DefaultRequestHeaders.Add("content-type", "application/json");
                    //client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");

                    string url = dynamicsOdataUri + dynamicsJobName;
                    Console.WriteLine(DateTime.Now + " Set full URL to speak to Dynamics: " + url);

                    HttpRequestMessage _httpRequest = new HttpRequestMessage(HttpMethod.Post, url);
                    _httpRequest.Content = new StringContent(model, Encoding.UTF8, "application/json");
                    //_httpRequest.Content = new StringContent(System.IO.File.ReadAllText(@"C:\Temp\VSD-RestSampleData3.txt"), Encoding.UTF8, "application/json");
                    Console.WriteLine(DateTime.Now + " Got HTTP Request ready");

                    var _httpResponse2 = await client.SendAsync(_httpRequest);

                    HttpStatusCode _statusCode = _httpResponse2.StatusCode;

                    var _responseString = _httpResponse2.ToString();
                    Console.WriteLine(DateTime.Now + " Got HTTP Response");//: " + _responseString);
                    var _responseContent2 = await _httpResponse2.Content.ReadAsStringAsync();

                    Console.Out.WriteLine(DateTime.Now + " model: " + model);
                    Console.Out.WriteLine(DateTime.Now + " responseString: " + _responseString);
                    Console.Out.WriteLine(DateTime.Now + " responseContent2: " + _responseContent2);

                    Console.WriteLine(DateTime.Now + " Exit GetDynamicsHttpClientNew");
                    return(new Tuple <int, HttpResponseMessage, string>((int)_statusCode, _httpResponse2, _responseContent2));
                    // End of scheduled task
                }
                catch (Exception e)
                {
                    return(new Tuple <int, HttpResponseMessage, string>(100, null, "Error"));

                    throw new Exception(e.Message + " " + _responseContent);
                }
            }
            else if (!string.IsNullOrEmpty(ssgUsername) && !string.IsNullOrEmpty(ssgPassword))
            // Authenticate using BASIC authentication - used for API Gateways with BASIC authentication.  Add the NTLM user associated with the API gateway entry to Dynamics as a user.
            {
                serviceClientCredentials = new BasicAuthenticationCredentials()
                {
                    UserName = ssgUsername,
                    Password = ssgPassword
                };
            }
            else
            {
                throw new Exception("No configured connection to Dynamics.");
            }

            return(new Tuple <int, HttpResponseMessage, string>(100, null, "Error"));
        }
        public static async Task <AuthenticationResult> AcquireGraphTokenByCodeAsync(this AuthenticationContext authContext, string code, ClientCredential clientCredential)
        {
            var token = await authContext.AcquireTokenByAuthorizationCodeAsync(
                code,
                new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                clientCredential,
                AppSettings.GraphResourceId
                );

            return(token);
        }
 public AdalAuthenticator(ClientCredential clientCredential, OAuthConfiguration configurationOAuth, HttpClient customHttpClient = null)
     : this(clientCredential, configurationOAuth, customHttpClient, null)
 {
 }
        public static ServiceClientCredentials GetServiceClientCredentials(IConfiguration configuration)
        {
            // Cloud - x.dynamics.com
            string aadTenantId              = configuration["DYNAMICS_AAD_TENANT_ID"];      // Cloud AAD Tenant ID
            string serverAppIdUri           = configuration["DYNAMICS_SERVER_APP_ID_URI"];  // Cloud Server App ID URI
            string appRegistrationClientKey = configuration["DYNAMICS_APP_REG_CLIENT_KEY"]; // Cloud App Registration Client Key
            string appRegistrationClientId  = configuration["DYNAMICS_APP_REG_CLIENT_ID"];  // Cloud App Registration Client Id

            // One Premise ADFS (2016)
            string adfsOauth2Uri            = configuration["ADFS_OAUTH2_URI"];              // ADFS OAUTH2 URI - usually /adfs/oauth2/token on STS
            string applicationGroupResource = configuration["DYNAMICS_APP_GROUP_RESOURCE"];  // ADFS 2016 Application Group resource (URI)
            string applicationGroupClientId = configuration["DYNAMICS_APP_GROUP_CLIENT_ID"]; // ADFS 2016 Application Group Client ID
            string applicationGroupSecret   = configuration["DYNAMICS_APP_GROUP_SECRET"];    // ADFS 2016 Application Group Secret
            string serviceAccountUsername   = configuration["DYNAMICS_USERNAME"];            // Service account username
            string serviceAccountPassword   = configuration["DYNAMICS_PASSWORD"];            // Service account password

            // API Gateway to NTLM user.  This is used in v8 environments.  Note that the SSG Username and password are not the same as the NTLM user.
            string ssgUsername = configuration["SSG_USERNAME"];  // BASIC authentication username
            string ssgPassword = configuration["SSG_PASSWORD"];  // BASIC authentication password



            ServiceClientCredentials serviceClientCredentials = null;

            if (!string.IsNullOrEmpty(appRegistrationClientId) && !string.IsNullOrEmpty(appRegistrationClientKey) && !string.IsNullOrEmpty(serverAppIdUri) && !string.IsNullOrEmpty(aadTenantId))
            // Cloud authentication - using an App Registration's client ID, client key.  Add the App Registration to Dynamics as an Application User.
            {
                var authenticationContext = new AuthenticationContext(
                    "https://login.windows.net/" + aadTenantId);
                ClientCredential clientCredential = new ClientCredential(appRegistrationClientId, appRegistrationClientKey);
                var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential);
                task.Wait();
                var    authenticationResult = task.Result;
                string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                serviceClientCredentials = new TokenCredentials(token);
            }
            if (!string.IsNullOrEmpty(adfsOauth2Uri) &&
                !string.IsNullOrEmpty(applicationGroupResource) &&
                !string.IsNullOrEmpty(applicationGroupClientId) &&
                !string.IsNullOrEmpty(applicationGroupSecret) &&
                !string.IsNullOrEmpty(serviceAccountUsername) &&
                !string.IsNullOrEmpty(serviceAccountPassword))
            // ADFS 2016 authentication - using an Application Group Client ID and Secret, plus service account credentials.
            {
                // create a new HTTP client that is just used to get a token.
                var stsClient = new HttpClient();

                //stsClient.DefaultRequestHeaders.Add("x-client-SKU", "PCL.CoreCLR");
                //stsClient.DefaultRequestHeaders.Add("x-client-Ver", "5.1.0.0");
                //stsClient.DefaultRequestHeaders.Add("x-ms-PKeyAuth", "1.0");

                stsClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString());
                stsClient.DefaultRequestHeaders.Add("return-client-request-id", "true");
                stsClient.DefaultRequestHeaders.Add("Accept", "application/json");

                // Construct the body of the request
                var pairs = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("resource", applicationGroupResource),
                    new KeyValuePair <string, string>("client_id", applicationGroupClientId),
                    new KeyValuePair <string, string>("client_secret", applicationGroupSecret),
                    new KeyValuePair <string, string>("username", serviceAccountUsername),
                    new KeyValuePair <string, string>("password", serviceAccountPassword),
                    new KeyValuePair <string, string>("scope", "openid"),
                    new KeyValuePair <string, string>("response_mode", "form_post"),
                    new KeyValuePair <string, string>("grant_type", "password")
                };

                // This will also set the content type of the request
                var content = new FormUrlEncodedContent(pairs);
                // send the request to the ADFS server
                var _httpResponse    = stsClient.PostAsync(adfsOauth2Uri, content).GetAwaiter().GetResult();
                var _responseContent = _httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                // response should be in JSON format.
                try
                {
                    Dictionary <string, string> result = JsonConvert.DeserializeObject <Dictionary <string, string> >(_responseContent);
                    string token = result["access_token"];
                    // set the bearer token.
                    serviceClientCredentials = new TokenCredentials(token);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message + " " + _responseContent);
                }
            }
            else if (!string.IsNullOrEmpty(ssgUsername) && !string.IsNullOrEmpty(ssgPassword))
            // Authenticate using BASIC authentication - used for API Gateways with BASIC authentication.  Add the NTLM user associated with the API gateway entry to Dynamics as a user.
            {
                serviceClientCredentials = new BasicAuthenticationCredentials
                {
                    UserName = ssgUsername,
                    Password = ssgPassword
                };
            }
            else
            {
                throw new Exception("No configured connection to Dynamics.");
            }

            return(serviceClientCredentials);
        }
Esempio n. 35
0
            async Task OnTokenValidated(JwtBearer.TokenValidatedContext tokenValidatedContext)
            {
                var passed = false;

                var identity = (ClaimsIdentity)tokenValidatedContext.Principal.Identity;

                // See if there's a UPN, and if so, use that object id
                var upn = identity.Claims.FirstOrDefault(c => c.Type == "upn")?.Value;

                if (upn != null)
                {
                    var oid = identity.Claims.FirstOrDefault(c => c.Type == "oid")?.Value;

                    // get the user
                    var context    = new AuthenticationContext($"{_azureOptions.AADInstance}{_azureOptions.TenantId}", null); // No token caching
                    var credential = new ClientCredential(_azureOptions.ClientId, _azureOptions.ClientSecret);

                    var incomingToken = ((JwtSecurityToken)tokenValidatedContext.SecurityToken).RawData;

                    // Prime the KV access token concurrently
                    var kvService   = contextAccessor.HttpContext.RequestServices.GetRequiredService <IKeyVaultService>();
                    var kvTokenTask = kvService.InitializeAccessTokenAsync(incomingToken);
                    var result      = await context.AcquireTokenAsync(graphResourceId, credential, new UserAssertion(incomingToken));



                    var       url  = $"{adminOptions.Value.GraphInstance}{_azureOptions.TenantId}/users/{oid}?api-version=1.6";
                    GraphUser user = null;
                    using (var client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        var resp = await client.GetAsync(url).ConfigureAwait(false);

                        if (resp.IsSuccessStatusCode)
                        {
                            user = JsonConvert.DeserializeObject <GraphUser>(await resp.Content.ReadAsStringAsync().ConfigureAwait(false));
                        }
                    }

                    if (user?.SignServiceConfigured == true)
                    {
                        passed = true;

                        identity.AddClaim(new Claim("keyVaultUrl", user.KeyVaultUrl));
                        identity.AddClaim(new Claim("keyVaultCertificateName", user.KeyVaultCertificateName));
                        identity.AddClaim(new Claim("timestampUrl", user.TimestampUrl));
                        identity.AddClaim(new Claim("access_token", incomingToken));
                    }

                    // Wait for the KV task to finish
                    await kvTokenTask.ConfigureAwait(false);

                    kvService.InitializeCertificateInfo(user.TimestampUrl, user.KeyVaultUrl, user.KeyVaultCertificateName);
                }

                if (!passed)
                {
                    // If we get here, it's an unknown value
                    tokenValidatedContext.Fail("User is not configured");
                }

                telemetryClient.Context.User.AuthenticatedUserId = upn;
            }
Esempio n. 36
0
        /// <summary>
        /// Configure Auth
        /// </summary>
        /// <param name="app">App builder</param>
        /// <param name="container">DI container</param>
        public void ConfigureAuth(IAppBuilder app, Autofac.IContainer container)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var validUpns = ConfigurationManager.AppSettings["ValidUpns"]
                            ?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                            ?.Select(s => s.Trim())
                            ?? new string[0];

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions("AppLogin")
            {
                ClientId              = clientId,
                Authority             = authority,
                RedirectUri           = redirectUri,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = (context) =>
                    {
                        var upnClaim = context?.AuthenticationTicket?.Identity?.Claims?
                                       .FirstOrDefault(c => c.Type == ClaimTypes.Upn);
                        var upn = upnClaim?.Value;

                        if (upn == null ||
                            !validUpns.Contains(upn, StringComparer.OrdinalIgnoreCase))
                        {
                            context.OwinContext.Response.Redirect("/Account/InvalidUser?upn=" + upn);
                            context.HandleResponse();
                        }

                        return(Task.CompletedTask);
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            context.ProtocolMessage.Prompt = OpenIdConnectPrompt.Login;
                        }

                        return(Task.CompletedTask);
                    },
                },
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions(Constants.SharePointAppLoginAuthenticationType)
            {
                AuthenticationMode         = AuthenticationMode.Passive,
                ClientId                   = ConfigurationManager.AppSettings["GraphAppClientId"],
                ClientSecret               = ConfigurationManager.AppSettings["GraphAppClientSecret"],
                Authority                  = authority,
                RedirectUri                = redirectUri,
                PostLogoutRedirectUri      = postLogoutRedirectUri,
                SignInAsAuthenticationType = Constants.SharePointAppLoginAuthenticationType,
                Notifications              = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var authContext = new AuthenticationContext(context.Options.Authority);
                        var credential  = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);

                        var tokenResponse = await authContext.AcquireTokenByAuthorizationCodeAsync(context.Code, new Uri(redirectUri), credential, context.Options.ClientId);

                        var tokenHelper = container.Resolve <TokenHelper>();
                        var upn         = context.AuthenticationTicket.Identity.Name;
                        await tokenHelper.SetSharePointUserAsync(upn, tokenResponse.AccessToken);
                    },

                    RedirectToIdentityProvider = (context) =>
                    {
                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            context.ProtocolMessage.Prompt = OpenIdConnectPrompt.Login;
                        }

                        return(Task.CompletedTask);
                    },
                },
            });
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Upn;
        }
        public static async Task <AuthenticationResult> AcquireGraphTokenByCodeAsync(this AuthenticationContext authContext, string code)
        {
            var clientCredential = new ClientCredential(AppSettings.ClientId, AppSettings.ClientSecret);

            return(await authContext.AcquireGraphTokenByCodeAsync(code, clientCredential));
        }
Esempio n. 38
0
        private static async Task <ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config)
        {
            ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);

            return(await ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure));
        }
Esempio n. 39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebApiDataAccessProxy"/> class.
 /// </summary>
 /// <param name="credential">The client credential used for consuming the data access functionalities.</param>
 public WebApiDataAccessProxy(ClientCredential credential) : base(credential)
 {
     this.serviceProxy = new ServiceProxy(credential);
 }
Esempio n. 40
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = Constants.AADClientId,
                Authority = Constants.Authority,

                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,
                },

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example) without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        var loginHint = context.Request.Query.Get("loginHint");
                        if (!string.IsNullOrEmpty(loginHint))
                        {
                            context.ProtocolMessage.LoginHint = loginHint;
                        }

                        var prompt = context.Request.Query.Get("prompt");
                        if (!string.IsNullOrEmpty(prompt))
                        {
                            context.ProtocolMessage.Prompt = prompt;
                        }

                        return(Task.FromResult(0));
                    },

                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = async context =>
                    {
                        var identity = context.AuthenticationTicket.Identity;

                        // Get token with authorization code
                        var redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        var credential  = new ClientCredential(Constants.AADClientId, Constants.AADClientSecret);

                        var authContext = AuthenticationHelper.GetAuthenticationContext(identity, Permissions.Delegated);
                        await authContext.AcquireTokenByAuthorizationCodeAsync(context.Code, redirectUri, credential, Constants.Resources.MSGraph);
                    },

                    AuthenticationFailed = context =>
                    {
                        if (context.Exception is OpenIdConnectProtocolException &&
                            (context.Exception.Message == "login_required" || context.Exception.Message == "interaction_required"))
                        {
                            context.Response.Redirect("/Tab/SignInRequired");
                            context.HandleResponse();
                        }
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Esempio n. 41
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            string clientID        = ConfigurationManager.AppSettings["ida:ClientID"];
            string aadInstance     = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant          = ConfigurationManager.AppSettings["ida:Tenant"];
            string clientSecret    = ConfigurationManager.AppSettings["ida:AppKey"];
            string graphResourceID = ConfigurationManager.AppSettings["ida:GraphResourceID"];

            string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = clientID,
                Authority = authority,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // when an auth code is received...
                    AuthorizationCodeReceived = (context) =>
                    {
                        // get the OpenID Connect code passed from Azure AD on successful auth
                        string code = context.Code;

                        // create the app credentials & get reference to the user
                        ClientCredential creds = new ClientCredential(clientID, clientSecret);
                        string tenantID        = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signInUserId    = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        // successful auth
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        context.ProtocolMessage.Prompt = "login";
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        return(Task.FromResult(0));
                    },
                    // we use this notification for injecting our custom logic
                    SecurityTokenValidated = (context) =>
                    {
                        // retriever caller data from the incoming principal
                        string issuer   = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                        string UPN      = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
                        string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                        //if (
                        //    // the caller comes from an admin-consented, recorded issuer
                        //    (db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null)
                        //    // the caller is recorded in the db of users who went through the individual onboardoing
                        //    && (db.Users.FirstOrDefault(b => ((b.UPN == UPN) && (b.TenantID == tenantID))) == null)
                        //    )
                        //    // the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow
                        //    throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.OwinContext.Response.Redirect("/Home/Error");
                        context.HandleResponse();     // Suppress the exception
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Esempio n. 42
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = AADAppSettings.ClientId,
                Authority = AADAppSettings.Authority,

                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // instead of using the default validation (validating against a single issuer value, as we do in line of business apps (single tenant apps)),
                    // we turn off validation
                    //
                    // NOTE:
                    // * In a multitenant scenario you can never validate against a fixed issuer string, as every tenant will send a different one.
                    // * If you don’t care about validating tenants, as is the case for apps giving access to 1st party resources, you just turn off validation.
                    // * If you do care about validating tenants, think of the case in which your app sells access to premium content and you want to limit access only to the tenant that paid a fee,
                    //       you still need to turn off the default validation but you do need to add logic that compares the incoming issuer to a list of tenants that paid you,
                    //       and block access if that’s not the case.
                    // * Refer to the following sample for a custom validation logic: https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet

                    ValidateIssuer = 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(AADAppSettings.ClientId, AADAppSettings.AppKey);
                        string tenantID             = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signedInUserID       = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", AADAppSettings.AuthorizationUri, tenantID), new NaiveSessionCache(signedInUserID));

                        // Get the access token for AAD Graph. Doing this will also initialize the token cache associated with the authentication context
                        // In theory, you could acquire token for any service your application has access to here so that you can initialize the token cache
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code,
                                                                                                  new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                                                                                  credential,
                                                                                                  AADAppSettings.GraphResourceId);

                        return(Task.FromResult(0));
                    },

                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        return(Task.FromResult(0));
                    },

                    AuthenticationFailed = (context) =>
                    {
                        // Suppress the exception
                        context.HandleResponse();

                        return(Task.FromResult(0));
                    }
                }
            });
        }