private async static Task<string> GetAccessTokenAsync(AuthenticationContext context, string[] scope)
        {
            if (AuthenticationParentUiContext == null)
            {
                throw new InvalidOperationException("The authentication parent is invalid");
            }

            AuthenticationResult result = await context.AcquireTokenAsync(
                            scope: scope,
                            additionalScope: null,
                            clientId: ClientId,
                            redirectUri: RedirectUri,
                            parameters: AuthenticationParentUiContext);

            if (!string.IsNullOrEmpty(result.Token))
            {
                AccessToken = result.Token;
                LoggedInUser = result.UserInfo.Name;
                LoggedInUserEmail = result.UserInfo.DisplayableId;
                LastTenantId = result.TenantId;
            }
            else
            {
                return null;
            }

            return AccessToken;
        }
        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");
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            SetIncidentId();

            DefaultTokenCacheStore cache = new DefaultTokenCacheStore(this);

            authContext = new AuthenticationContext(this,
                Constants.AAD_AUTHORITY,
                false,
                cache);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.signIn_btn);

            button.Click += delegate
            {
                authContext.AcquireToken(this,
                    Constants.SHAREPOINT_URL,
                    Constants.AAD_CLIENT_ID,
                    Constants.AAD_REDIRECT_URL,
                    PromptBehavior.RefreshSession,
                    new SignInCallback(this));
            };
        }
Ejemplo n.º 4
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));
            }
        }
Ejemplo n.º 5
0
        public static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Client ready.");
            Console.WriteLine("Press any key to invoke the service");
            Console.WriteLine("Press ESC to terminate");
            ConsoleKeyInfo consoleKeyInfo;

            var authenticationContext = new AuthenticationContext("https://login.windows.net/SalesApplication.onmicrosoft.com");

            do
            {
                consoleKeyInfo = Console.ReadKey(true);
                // get the access token
                AuthenticationResult authenticationResult = authenticationContext.AcquireToken(
                    "https://SalesApplication.onmicrosoft.com/NancyDemoServer",
                    "5461d04d-d248-47dd-8008-076458153331",
                    "https://SalesApplication.onmicrosoft.com/nancyDemoNativeClient");

                // invoke the Nancy API
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                HttpResponseMessage response = httpClient.GetAsync("http://localhost:9000/values").Result;
                // display the result
                if (response.IsSuccessStatusCode)
                {
                    string result = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine("==> Successfully invoked the service");
                    Console.WriteLine(result);
                }
            } while (consoleKeyInfo.Key != ConsoleKey.Escape);
        }
Ejemplo n.º 6
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}");
            }
        }
Ejemplo n.º 7
0
        private Office365Api()
        {
            // use file cache to persist token
            _authContext = new AuthenticationContext(_authority, new FileCache());

            if (_authContext.TokenCache.ReadItems().Count() > 0)
            {
                // re-bind the AuthenticationContext to the authority that sourced the token in the cache 
                // this is needed for the cache to work when asking a token from that authority 
                // (the common endpoint never triggers cache hits) 
                var cachedAuthority = _authContext.TokenCache.ReadItems().First().Authority;
                _authContext = new AuthenticationContext(cachedAuthority, new FileCache());
            }
            else
            {
                // no previous tokens -> do nothing for now
            }

            // initialize outlook services client
            _client = new OutlookServicesClient(new Uri(_apiUrl), async () =>
            {
                // Since we have it locally from the Session, just return it here.
                return _authResult.Token;
            });
        }
    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("/");
    }
Ejemplo n.º 9
0
 public CurrentUser(AuthenticationContext authContext, IEventAggregator eventMgr)
 {
     _authContext = authContext;
     EventManager = eventMgr;
     Instance = this;
     EventManager.GetEvent<LogonEvent>().Subscribe(HandleLogonEvent);
     EventManager.GetEvent<LogoffEvent>().Subscribe(HandleLogoffEvent);
 }
		static OAuthProperties()
		{
			var context = new AuthenticationContext();

			AccessToken = context.AccessToken;
			AccessTokenSecret = context.AccessTokenSecret;
			ConsumerKey = context.ConsumerKey;
			ConsumerKeySecret = context.ConsumerKeySecret;
		}
Ejemplo n.º 11
0
		private static HttpWebRequest GetTimelineRequest(AuthenticationContext authenticationContext, string screenName)
		{
			var requestBuilder = new RequestBuilder(authenticationContext);
			var requestParameters = new TimelineRequestParameters(authenticationContext)
			{
				ScreenName = screenName,
				Count = "10",
			};

			return requestBuilder.GetRequest(requestParameters);
		}
Ejemplo n.º 12
0
 private string GetUserEmail(AuthenticationContext context, string clientId)
 {
     // ADAL caches the ID token in its token cache by the client ID
     foreach (TokenCacheItem item in context.TokenCache.ReadItems())
     {
         if (item.Scope.Contains(clientId))
         {
             return GetEmailFromIdToken(item.Token);
         }
     }
     return string.Empty;
 }
        private void GetTokenButton_Click(object sender, RoutedEventArgs e)
        {
            var context = new AuthenticationContext(Constants.ACS.IssuerUri);
            var credential = context.AcquireToken(Constants.Realm);

            if (credential != null)
            {
                if (!string.IsNullOrWhiteSpace(credential.Assertion))
                {
                    _token = credential.Assertion;
                    OutputTextBox.Text = _token;
                }
            }
        }
Ejemplo n.º 14
0
        public async Task<IActionResult> SignIn()
        {
            string authority = "https://login.microsoftonline.com/common";
            AuthenticationContext authContext = new AuthenticationContext(authority);

            Uri redirectUri = new Uri(Url.Action("Authorize", "Outlook", null, "http"));

            // Generate the parameterized URL for Azure signin
            Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, ClientId,
                redirectUri, UserIdentifier.AnyUser, null);

            // Redirect the browser to the Azure signin page
            return Redirect(authUri.ToString());
        }
Ejemplo n.º 15
0
        public async Task<ActionResult> SignIn()
        {
            string authority = "https://login.microsoftonline.com/common";
            string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"]; 
            AuthenticationContext authContext = new AuthenticationContext(authority);

            // The url in our app that Azure should redirect to after successful signin
            Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

            // Generate the parameterized URL for Azure signin
            Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, clientId, redirectUri, UserIdentifier.AnyUser, null);

            // Redirect the browser to the Azure signin page
            return Redirect(authUri.ToString());
        }
Ejemplo n.º 16
0
 public async Task<IAuthToken> GetAuthTokenAsync()
 {
     //ClearAllTokensCache();
     var settings = this.SettingsRepo.GetSettings();
     var authenticationContext = new AuthenticationContext(settings.LoginURL);
     var result = await authenticationContext.AcquireTokenAsync(settings.DirectoryServiceURL, settings.ClientID);
     if(result.Status == AuthenticationStatus.Succeeded)
     {
         IAuthToken aadToken = new AADJWTToken();
         aadToken.AccessToken = result.AccessToken;
         return aadToken;
     }
     else
     {
         throw new Exception(result.Error + " " + result.ErrorDescription);
     }
 }
Ejemplo n.º 17
0
        public async System.Threading.Tasks.Task<AuthenticationResult> Authenticate(string authority, string clientId, string returnUri, string policy)
        {
            var authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any())
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);

            var platformParams = new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController);


            //var authResult = await authContext.AcquireTokenAsync(new string[] { clientId }, null, clientId, new Uri(returnUri), platformParams, "B2C_1_TestB2C");
            var authResult = await authContext.AcquireTokenAsync(new string[] { clientId }, null, clientId, new Uri(returnUri), platformParams, policy);

            

            //var authResult = await authContext.AcquireTokenAsync(resource, clientId, new Uri(returnUri),
            //    new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController));
            return authResult;
        }
Ejemplo n.º 18
0
        public async Task<AuthenticationResult> Authenticate(string authority, string clientId, string returnUri, string policy)
        {
            
            AuthenticationContext authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any())
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);

            // var platformParams = new PlatformParameters((Activity)Forms.Context);


            //var authResult = await authContext.AcquireTokenAsync(new string[] { clientId }, null, clientId, new Uri(returnUri), platformParams, "B2C_1_TestB2C");

            AuthenticationResult authResult = await authContext.AcquireTokenAsync(new string[] { clientId }, null, clientId, new Uri(returnUri), new PlatformParameters((Activity)Forms.Context), policy);

            //var authResult = await authContext.AcquireTokenAsync(resource, clientId, new Uri(returnUri), new PlatformParameters((Activity)Forms.Context));

            
            return authResult;
        }
    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();
    }
Ejemplo n.º 20
0
        public static List <Organization> GetUserOrganizations()
        {
            List <Organization> organizations = new List <Organization>();

            string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserUniqueName));

                var items = authContext.TokenCache.ReadItems().ToList();


                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                items = authContext.TokenCache.ReadItems().ToList();


                // Get a list of Organizations of which the user is a member
                string requestUrl = string.Format("{0}/tenants?api-version={1}", ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"],
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Tenant Objects
                // id                                            tenantId
                // --                                            --------
                // /tenants/7fe877e6-a150-4992-bbfe-f517e304dfa0 7fe877e6-a150-4992-bbfe-f517e304dfa0
                // /tenants/62e173e9-301e-423e-bcd4-29121ec1aa24 62e173e9-301e-423e-bcd4-29121ec1aa24

                if (response.IsSuccessStatusCode)
                {
                    string responseContent     = response.Content.ReadAsStringAsync().Result;
                    var    organizationsResult = (Json.Decode(responseContent)).value;

                    foreach (var organization in organizationsResult)
                    {
                        organizations.Add(new Organization()
                        {
                            Id = organization.tenantId,
                            //DisplayName = AzureADGraphAPIUtil.GetOrganizationDisplayName(organization.tenantId),
                            objectIdOfISVDemoUsageServicePrincipal =
                                AzureADGraphAPIUtil.GetObjectIdOfServicePrincipalInOrganization(organization.tenantId, ConfigurationManager.AppSettings["ida:ClientID"])
                        });
                    }
                }
            }
            catch
            {
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserUniqueName));

                var items = authContext.TokenCache.ReadItems().ToList();


                AuthenticationResult result = authContext.AcquireToken(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential);


                //(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                //new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                items = authContext.TokenCache.ReadItems().ToList();


                // Get a list of Organizations of which the user is a member
                string requestUrl = string.Format("{0}/tenants?api-version={1}", ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"],
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Tenant Objects
                // id                                            tenantId
                // --                                            --------
                // /tenants/7fe877e6-a150-4992-bbfe-f517e304dfa0 7fe877e6-a150-4992-bbfe-f517e304dfa0
                // /tenants/62e173e9-301e-423e-bcd4-29121ec1aa24 62e173e9-301e-423e-bcd4-29121ec1aa24

                if (response.IsSuccessStatusCode)
                {
                    string responseContent     = response.Content.ReadAsStringAsync().Result;
                    var    organizationsResult = (Json.Decode(responseContent)).value;

                    foreach (var organization in organizationsResult)
                    {
                        organizations.Add(new Organization()
                        {
                            Id = organization.tenantId,
                            //DisplayName = AzureADGraphAPIUtil.GetOrganizationDisplayName(organization.tenantId),
                            objectIdOfISVDemoUsageServicePrincipal =
                                AzureADGraphAPIUtil.GetObjectIdOfServicePrincipalInOrganization(organization.tenantId, ConfigurationManager.AppSettings["ida:ClientID"])
                        });
                    }
                }
            }
            return(organizations);
        }
Ejemplo n.º 21
0
 private Task<AuthenticationResult> GetAuthAsync()
 {
     var tcs = new TaskCompletionSource<AuthenticationResult>();
     AuthenticationResult res = null;
     Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
         {
             AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/common");
             try
             {
                 // Idea here is to always call AcquireToken and it will deal with caching and refresh, etc..
                 res = await ac.AcquireTokenAsync(Resource, ClientId, redirectUri);
                 tcs.SetResult(res);
             }
             catch (Exception ex)
             {
                 tcs.SetException(ex);
             }
         });
     return tcs.Task;
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Get the token for authenticating requests to Azure Resource Manager in customer tenant.
        /// </summary>
        /// <param name="appId">appid that is registered for this application in Azure Active Directory (AAD)</param>
        /// <param name="key">This is the key for this application in Azure Active Directory</param>
        /// <param name="customerTenantId">cid of the customer</param>
        /// <returns>Azure Auth Token in the context of the customer tenant.</returns>
        private static AuthenticationResult GetAzureAuthTokenForCustomerTenant(string appId, string credentialName, string customerTenantId)
        {
            AuthenticationResult authResult = null;
            string resource = "https://management.core.windows.net/";

            var authenticationContext = new AuthenticationContext("https://login.windows.net/" + customerTenantId);
            try
            {
                authResult = authenticationContext.AcquireTokenSilent(resource: resource, clientId: appId);
            }
            catch (AdalException aex)
            {
                if (aex.ErrorCode == "failed_to_acquire_token_silently")
                {
                    UserCredential uc = CredentialManager.GetCredential(credentialName);
                    authResult = authenticationContext.AcquireToken(resource: resource, clientId: appId, userCredential: uc);
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return authResult;
        }
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The service collection.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(opts =>
            {
                opts.Filters.Add(typeof(AdalTokenAcquisitionExceptionFilterAttribute));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddDataProtection();

            // Wiring up App Insights
            services.AddApplicationInsightsTelemetry();
            services.AddSingleton <IKeyVaultHelper, KeyVaultHelper>();
            services.AddSingleton <AppSettings>();
            services.AddSingleton <IApiHelper, ApiHelper>();

            var serviceProvider = services.BuildServiceProvider();
            var appSettings     = serviceProvider.GetService <AppSettings>();

            // Add a strongly-typed options class to DI
            services.Configure <AuthOptionsModel>(opt =>
            {
                opt.Authority    = appSettings.Authority;
                opt.ClientId     = appSettings.ClientId;
                opt.ClientSecret = appSettings.ClientSecret;
            });

            services.AddScoped <ITokenCacheFactory, TokenCacheFactory>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = appSettings.RedisCacheConfiguration;
                options.InstanceName  = this.Configuration["RedisCacheInstanceName"];
            });

            services.AddHttpClient("ShiftsKronosIntegrationAPI", c =>
            {
                c.BaseAddress = new Uri(this.Configuration["BaseAddressFirstTimeSync"]);
                c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }).AddPolicyHandler(GetRetryPolicy());

            services.AddHttpClient("GraphBetaAPI", client =>
            {
                client.BaseAddress = new Uri(this.Configuration["GraphApiUrl"]);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }).AddPolicyHandler(GetRetryPolicy());

            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
                auth.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(opts =>
            {
                opts.SlidingExpiration = true;
                opts.AccessDeniedPath  = new PathString("/Account/AccessDenied");
            })
            .AddOpenIdConnect(
                opts =>
            {
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
                opts.Events.OnTicketReceived = async(context) =>
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
                {
                    context.Properties.ExpiresUtc = DateTime.UtcNow.AddHours(1);
                };

                opts.ClientId     = this.Configuration["ClientId"];
                opts.ClientSecret = this.Configuration["ClientSecret"];
                opts.Authority    = this.Configuration["Authority"];
                opts.ResponseType = this.Configuration["ResponseType"];

                this.Configuration.Bind(opts);
                opts.TokenValidationParameters.ValidateIssuer = false;
                opts.Events = new OpenIdConnectEvents
                {
                    OnAuthorizationCodeReceived = async ctx =>
                    {
                        HttpRequest request = ctx.HttpContext.Request;

                        // We need to also specify the redirect URL used
                        string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);

                        // Credentials for app itself
                        var credential = new ClientCredential(appSettings.ClientId, appSettings.ClientSecret);

                        // Construct token cache
                        var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService <IDistributedCache>();
                        var cache            = new RedisTokenCache(distributedCache, appSettings.ClientId);

                        var authContext = new AuthenticationContext("https://login.microsoftonline.com/common", cache);

                        // Get token for Microsoft Graph API using the authorization code
                        string resource             = "https://graph.microsoft.com";
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            ctx.ProtocolMessage.Code, new Uri(currentUri), credential, resource).ConfigureAwait(false);

                        // Tell the OIDC middleware we got the tokens, it doesn't need to do anything
                        ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    },
                };
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();
            services.AddHttpClient();

            // As each sub-integration is being implemented, we need to make sure that we can correctly setup the DI.g
            services.AddSingleton <BusinessLogic.Providers.IConfigurationProvider>((provider) => new BusinessLogic.Providers.ConfigurationProvider(
                                                                                       appSettings.StorageConnectionString,
                                                                                       provider.GetRequiredService <TelemetryClient>()));
            services.AddSingleton <ITeamDepartmentMappingProvider>((provider) => new TeamDepartmentMappingProvider(
                                                                       appSettings.StorageConnectionString,
                                                                       provider.GetRequiredService <TelemetryClient>()));
            services.AddSingleton <IUserMappingProvider>((provider) => new UserMappingProvider(
                                                             appSettings.StorageConnectionString,
                                                             provider.GetRequiredService <TelemetryClient>()));
            services.AddSingleton <IGraphUtility>((provider) => new GraphUtility(
                                                      provider.GetRequiredService <TelemetryClient>(),
                                                      provider.GetRequiredService <IDistributedCache>(),
                                                      provider.GetRequiredService <System.Net.Http.IHttpClientFactory>()));
            services.AddSingleton <ShiftsTeamKronosDepartmentViewModel>();
            services.AddSingleton <IShiftMappingEntityProvider>((provider) => new ShiftMappingEntityProvider(
                                                                    provider.GetRequiredService <TelemetryClient>(),
                                                                    appSettings.StorageConnectionString));
            services.AddSingleton <IOpenShiftMappingEntityProvider>((provider) => new OpenShiftMappingEntityProvider(
                                                                        provider.GetRequiredService <TelemetryClient>(),
                                                                        appSettings.StorageConnectionString));
            services.AddSingleton <ITimeOffMappingEntityProvider>((provider) => new TimeOffMappingEntityProvider(
                                                                      provider.GetRequiredService <TelemetryClient>(),
                                                                      appSettings.StorageConnectionString));
            services.AddSingleton <IAzureTableStorageHelper>((provider) => new AzureTableStorageHelper(
                                                                 appSettings.StorageConnectionString,
                                                                 provider.GetRequiredService <TelemetryClient>()));
            services.AddSingleton((provider) => new Utility(
                                      provider.GetRequiredService <TelemetryClient>(),
                                      provider.GetRequiredService <ILogonActivity>(),
                                      provider.GetRequiredService <AppSettings>(),
                                      provider.GetRequiredService <IDistributedCache>(),
                                      provider.GetRequiredService <BusinessLogic.Providers.IConfigurationProvider>(),
                                      provider.GetRequiredService <IAzureTableStorageHelper>(),
                                      provider.GetRequiredService <IGraphUtility>()));

            services.AddSingleton((provider) => new TeamDepartmentMappingController(
                                      provider.GetRequiredService <ITeamDepartmentMappingProvider>(),
                                      provider.GetRequiredService <TelemetryClient>(),
                                      provider.GetRequiredService <ILogonActivity>(),
                                      provider.GetRequiredService <IHyperFindLoadAllActivity>(),
                                      provider.GetRequiredService <ShiftsTeamKronosDepartmentViewModel>(),
                                      provider.GetRequiredService <IGraphUtility>(),
                                      provider.GetRequiredService <AppSettings>(),
                                      provider.GetRequiredService <BusinessLogic.Providers.IConfigurationProvider>(),
                                      provider.GetRequiredService <IDistributedCache>(),
                                      provider.GetRequiredService <IUserMappingProvider>(),
                                      provider.GetRequiredService <System.Net.Http.IHttpClientFactory>()));

            services.AddSingleton((provider) => new UserMappingController(
                                      provider.GetRequiredService <AppSettings>(),
                                      provider.GetRequiredService <IGraphUtility>(),
                                      provider.GetRequiredService <ILogonActivity>(),
                                      provider.GetRequiredService <IHyperFindActivity>(),
                                      provider.GetRequiredService <TelemetryClient>(),
                                      provider.GetRequiredService <IUserMappingProvider>(),
                                      provider.GetRequiredService <ITeamDepartmentMappingProvider>(),
                                      provider.GetRequiredService <BusinessLogic.Providers.IConfigurationProvider>(),
                                      provider.GetRequiredService <IJobAssignmentActivity>(),
                                      provider.GetRequiredService <IHostingEnvironment>(),
                                      provider.GetRequiredService <Utility>()));

            // Wiring up Kronos dependency chain to set up DI container.
            services.AddSingleton <App.KronosWfc.Models.RequestEntities.Logon.Request>();
            services.AddSingleton <ILogonActivity, LogonActivity>((provider) => new LogonActivity(
                                                                      new App.KronosWfc.Models.RequestEntities.Logon.Request(),
                                                                      provider.GetRequiredService <TelemetryClient>(),
                                                                      provider.GetRequiredService <IApiHelper>()));
            services.AddSingleton <IHyperFindLoadAllActivity, HyperFindLoadAllActivity>((provider) => new HyperFindLoadAllActivity(
                                                                                            provider.GetRequiredService <TelemetryClient>(),
                                                                                            provider.GetRequiredService <IApiHelper>()));
            services.AddSingleton <IHyperFindActivity, HyperFindActivity>((provider) => new HyperFindActivity(
                                                                              provider.GetRequiredService <TelemetryClient>(),
                                                                              provider.GetRequiredService <IApiHelper>()));
            services.AddSingleton <IJobAssignmentActivity, JobAssignmentActivity>((provider) => new JobAssignmentActivity(
                                                                                      provider.GetRequiredService <TelemetryClient>(),
                                                                                      provider.GetRequiredService <IApiHelper>()));
        }
        public static async Task<GraphService> GetGraphClientAsync(string[] scope)
        {
            if (graphClient == null)
            {
                try
                {
                    AuthenticationContext = new AuthenticationContext(CommonAuthority, new TokenCache());

                    var token = await GetAccessTokenAsync(AuthenticationContext, scope);
                    if (string.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return null;
                    }
                    else
                    {
                        var tenantId = (LastTenantId ?? "outlook.com") + "/";
                        Uri serviceRoot = new Uri(ResourceBetaUrl + tenantId);
                        graphClient = new GraphService(serviceRoot, async () => await GetAccessTokenAsync(AuthenticationContext, scope));
                    }
                }
                catch (AdalException ex)
                {
                    Debug.WriteLine("Error from Adal: " + ex.ToString());
                    AuthenticationContext.TokenCache.Clear();
                    return null;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception thrown: " + ex.ToString());
                    AuthenticationContext.TokenCache.Clear();
                    return null;
                }
            }

            return graphClient;
        }
        private async void buttonPickupAccount_Click(object sender, EventArgs e)
        {
            AddAMSAccount1 addaccount1 = new AddAMSAccount1();

            if (addaccount1.ShowDialog() == DialogResult.OK)
            {
                if (addaccount1.SelectedMode == AddAccountMode.BrowseSubscriptions)
                {
                    environment = addaccount1.GetEnvironment();

                    AuthenticationContext authContext = new AuthenticationContext(
                        // authority:  environment.Authority,
                        authority: environment.AADSettings.AuthenticationEndpoint.ToString() + "common",
                        validateAuthority: true
                        );

                    AuthenticationResult accessToken;
                    try
                    {
                        accessToken = await authContext.AcquireTokenAsync(
                            resource : environment.AADSettings.TokenAudience.ToString(),
                            clientId : environment.ClientApplicationId,
                            redirectUri : new Uri("urn:ietf:wg:oauth:2.0:oob"),
                            parameters : new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto)
                            );
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    TokenCredentials credentials = new TokenCredentials(accessToken.AccessToken, "Bearer");

                    SubscriptionClient subscriptionClient = new SubscriptionClient(environment.ArmEndpoint, credentials);
                    Microsoft.Rest.Azure.IPage <Microsoft.Azure.Management.ResourceManager.Models.Subscription> subscriptions = subscriptionClient.Subscriptions.List();



                    // tenants browsing
                    myTenants tenants = new myTenants();
                    string    URL     = environment.ArmEndpoint + "tenants?api-version=2017-08-01";

                    HttpClient client = new HttpClient();
                    client.DefaultRequestHeaders.Remove("Authorization");
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken.AccessToken);
                    HttpResponseMessage response = await client.GetAsync(URL);

                    if (response.IsSuccessStatusCode)
                    {
                        string str = await response.Content.ReadAsStringAsync();

                        tenants = (myTenants)JsonConvert.DeserializeObject(str, typeof(myTenants));
                    }
                    AddAMSAccount2Browse addaccount2 = new AddAMSAccount2Browse(credentials, subscriptions, environment, tenants.value, new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto));

                    if (addaccount2.ShowDialog() == DialogResult.OK)
                    {
                        // Getting Media Services accounts...
                        AzureMediaServicesClient mediaServicesClient = new AzureMediaServicesClient(environment.ArmEndpoint, credentials);

                        CredentialsEntryV3 entry = new CredentialsEntryV3(addaccount2.selectedAccount,
                                                                          environment,
                                                                          addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto,
                                                                          false,
                                                                          addaccount2.selectedTenantId,
                                                                          false
                                                                          );
                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }


                // Get info from the Azure CLI JSON
                else if (addaccount1.SelectedMode == AddAccountMode.FromAzureCliJson)
                {
                    string        example = @"{
  ""AadClientId"": ""00000000-0000-0000-0000-000000000000"",
  ""AadEndpoint"": ""https://login.microsoftonline.com"",
  ""AadSecret"": ""00000000-0000-0000-0000-000000000000"",
  ""AadTenantId"": ""00000000-0000-0000-0000-000000000000"",
  ""AccountName"": ""amsaccount"",
  ""ArmAadAudience"": ""https://management.core.windows.net/"",
  ""ArmEndpoint"": ""https://management.azure.com/"",
  ""Region"": ""West Europe"",
  ""ResourceGroup"": ""amsResourceGroup"",
  ""SubscriptionId"": ""00000000-0000-0000-0000-000000000000""
}";
                    EditorXMLJSON form    = new EditorXMLJSON("Enter the JSON output of Azure Cli Service Principal creation (az ams account sp create)", example, true, false, true, "The Service Principal secret is stored encrypted in the application settings.");

                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        JsonFromAzureCli json = null;
                        try
                        {
                            json = (JsonFromAzureCli)JsonConvert.DeserializeObject(form.TextData, typeof(JsonFromAzureCli));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Error reading the json", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        string resourceId  = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Media/mediaservices/{2}", json.SubscriptionId, json.ResourceGroup, json.AccountName);
                        string AADtenantId = json.AadTenantId;

                        ActiveDirectoryServiceSettings aadSettings = new ActiveDirectoryServiceSettings()
                        {
                            AuthenticationEndpoint = json.AadEndpoint,
                            TokenAudience          = json.ArmAadAudience,
                            ValidateAuthority      = true
                        };

                        AzureEnvironment env = new AzureEnvironment(AzureEnvType.Custom)
                        {
                            AADSettings = aadSettings, ArmEndpoint = json.ArmEndpoint
                        };

                        CredentialsEntryV3 entry = new CredentialsEntryV3(
                            new SubscriptionMediaService(resourceId, json.AccountName, null, null, json.Region),
                            env,
                            PromptBehavior.Auto,
                            true,
                            AADtenantId,
                            false
                            )
                        {
                            ADSPClientId          = json.AadClientId,
                            ClearADSPClientSecret = json.AadSecret
                        };

                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }
                else if (addaccount1.SelectedMode == AddAccountMode.ManualEntry)
                {
                    AddAMSAccount2Manual form = new AddAMSAccount2Manual();
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        string accountnamecc = form.textBoxAMSResourceId.Text.Split('/').Last();

                        CredentialsEntryV3 entry = new CredentialsEntryV3(
                            new SubscriptionMediaService(form.textBoxAMSResourceId.Text, accountnamecc, null, null, form.textBoxLocation.Text),
                            addaccount1.GetEnvironment(),
                            PromptBehavior.Auto,
                            form.radioButtonAADServicePrincipal.Checked,
                            form.textBoxAADtenantId.Text,
                            true
                            );

                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
        private static async Task EnsureAccessTokenAsync()
        {
            if (AuthenticationContext == null)
            {
                AuthenticationContext = new AuthenticationContext(CommonAuthority, new TokenCache());
            }

            if (string.IsNullOrEmpty(AccessToken))
            {
                AccessToken = await GetAccessTokenAsync(AuthenticationContext, PermissionScope);
            }
        }
 public ActionResult Logout()
 {
   AuthenticationContext authContext = new AuthenticationContext(authority);
   authContext.TokenCache.Clear();
   return Redirect("/");
 }
    public AzureAdAuthenticationProvider()
    {
        var tenantId = "...";     // Get from configuration

        _authContext = new AuthenticationContext(string.Format(AuthorityFormatString, tenantId));
    }
Ejemplo n.º 29
0
        static async Task Main(string[] args)
        {
            configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();

            graphResourceId   = configuration["AzureAd:GraphResourceId"];
            azureRmResourceId = configuration["AzureAd:AzureRmResourceId"];
            authContext       = new AuthenticationContext($"{configuration["AzureAd:Instance"]}common");

            // Prompt here so we make sure we're in the right directory
            var token = await authContext.AcquireTokenAsync(graphResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.SelectAccount));

            authResult  = token;
            graphClient = new ActiveDirectoryClient(new Uri($"{graphResourceId}{token.TenantId}"), async() => (await authContext.AcquireTokenSilentAsync(graphResourceId, clientId)).AccessToken);

            if (args.Length > 0)
            {
                // Read a disambiguation value
                environment = $" ({args[0]}) ";
            }

            var serverDisplayNamePrefix = $"SignService Server{environment} - ";


            Guid   applicationId;
            string password = null;

            // Try to find a "SignService Server -" app
            var a = await graphClient.Applications.Where(ia => ia.DisplayName.StartsWith(serverDisplayNamePrefix)).ExecuteAsync();

            if (a.CurrentPage.Count == 1)
            {
                applicationId = Guid.Parse(a.CurrentPage[0].ObjectId);
                Console.WriteLine($"Found application '{a.CurrentPage[0].DisplayName}'");
                Console.WriteLine("Enter [Y/n] to continue: ");
                var key = Console.ReadLine().ToUpperInvariant().Trim();
                if (!(key == string.Empty || key == "Y"))
                {
                    Console.WriteLine("Exiting....");
                    return;
                }
            }
            else
            {
                var appName = $"{serverDisplayNamePrefix}{Guid.NewGuid()}";
                Console.WriteLine($"Creating application '{appName}'");
                // Create
                var newApp = await CreateApplication(appName);

                applicationId = newApp.Item1;
                password      = newApp.Item2;

                Console.WriteLine("Created application");
            }

            Console.WriteLine("Updating application....");
            var serverApp = await ConfigureApplication(applicationId);

            var clientApp = await EnsureClientAppExists(serverApp.application);

            Console.WriteLine("Update complete.");

            // If password is not null, we created the app, add the user admin role assignment
            if (!string.IsNullOrWhiteSpace(password))
            {
                await AddAdminRoleAssignmentToServer(serverApp.servicePrincipal);
            }

            // Prompt for consent
            await PromptForConsent(serverApp, clientApp);

            // Need to create a resource group and grant the sign service application the Read permissions
            await CreateOrUpdateResourceGroup(serverApp.servicePrincipal);

            // Print out relevant values
            PrintApplicationInfo(serverApp, password, clientApp);

            Console.WriteLine("Press any key to quit....");
            Console.ReadKey(true);
        }
Ejemplo n.º 30
0
        public static List <Subscription> GetUserSubscriptions(string organizationId)
        {
            List <Subscription> subscriptions = null;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId),
                    new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result =
                    authContext.AcquireTokenSilent(
                        ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                        new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                subscriptions = new List <Subscription>();

                // Get subscriptions to which the user has some kind of access
                string requestUrl = string.Format("{0}/subscriptions?api-version={1}",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"],
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                if (response.IsSuccessStatusCode)
                {
                    string responseContent     = response.Content.ReadAsStringAsync().Result;
                    var    subscriptionsResult = (Json.Decode(responseContent)).value;

                    foreach (var subscription in subscriptionsResult)
                    {
                        subscriptions.Add(new Subscription()
                        {
                            Id             = subscription.subscriptionId,
                            DisplayName    = subscription.displayName,
                            OrganizationId = organizationId
                        });
                    }
                }
            }
            catch
            {
                //ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                //   ConfigurationManager.AppSettings["ida:Password"]);
                //// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                //AuthenticationContext authContext = new AuthenticationContext(
                //    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                //string resource = ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"];


                //AuthenticationResult result = authContext.AcquireToken(resource, credential.ClientId,
                //    new UserCredential(signedInUserUniqueName));

                ////authContext.AcquireToken(resource,userAssertion:)

                //    //new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId)));

                //    //AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                //    //new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                //subscriptions = new List<Subscription>();

                //// Get subscriptions to which the user has some kind of access
                //string requestUrl = string.Format("{0}/subscriptions?api-version={1}", ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"],
                //    ConfigurationManager.AppSettings["ida:AzureResourceManagerAPIVersion"]);

                //// Make the GET request
                //HttpClient client = new HttpClient();
                //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                //HttpResponseMessage response = client.SendAsync(request).Result;

                //if (response.IsSuccessStatusCode)
                //{
                //    string responseContent = response.Content.ReadAsStringAsync().Result;
                //    var subscriptionsResult = (Json.Decode(responseContent)).value;

                //    foreach (var subscription in subscriptionsResult)
                //        subscriptions.Add(new Subscription()
                //        {
                //            Id = subscription.subscriptionId,
                //            DisplayName = subscription.displayName,
                //            OrganizationId = organizationId
                //        });
                //}
            }

            return(subscriptions);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Builds a connection string for the storage account when none was specified during initialisation.
        /// </summary>
        /// <returns>Connection <see cref="string" /></returns>
        /// <exception cref="InvalidOperationException">If the Storage Namespace can not be resolved or access keys are not configured.</exception>
        internal async Task <string> BuildStorageConnection()
        {
            try
            {
                // If we already have the connection string for this instance - don't go get it again.
                if (ConnectionStrings.TryGetValue(_instanceName, out var connStr))
                {
                    return(connStr);
                }

                const string azureManagementAuthority = "https://management.azure.com/";
                const string windowsLoginAuthority    = "https://login.windows.net/";
                string       token;

                // Use Msi Config if it's been specified, otherwise, use Service principle.
                if (MsiConfig != null)
                {
                    // Managed Service Identity (MSI) authentication.
                    var provider = new AzureServiceTokenProvider();
                    token = provider.GetAccessTokenAsync(azureManagementAuthority, MsiConfig.TenantId).GetAwaiter().GetResult();

                    if (string.IsNullOrEmpty(token))
                    {
                        throw new InvalidOperationException("Could not authenticate using Managed Service Identity, ensure the application is running in a secure context");
                    }

                    _expiryTime = DateTime.Now.AddDays(1);
                }
                else
                {
                    // Service Principle authentication
                    // Grab an authentication token from Azure.
                    var context = new AuthenticationContext($"{windowsLoginAuthority}{ServicePrincipleConfig.TenantId}");

                    var credential  = new ClientCredential(ServicePrincipleConfig.AppId, ServicePrincipleConfig.AppSecret);
                    var tokenResult = context.AcquireTokenAsync(azureManagementAuthority, credential).GetAwaiter().GetResult();

                    if (tokenResult == null || tokenResult.AccessToken == null)
                    {
                        throw new InvalidOperationException($"Could not authenticate to {windowsLoginAuthority}{ServicePrincipleConfig.TenantId} using supplied AppId: {ServicePrincipleConfig.AppId}");
                    }

                    _expiryTime = tokenResult.ExpiresOn;
                    token       = tokenResult.AccessToken;
                }

                // Set credentials and grab the authenticated REST client.
                var tokenCredentials = new TokenCredentials(token);

                var client = RestClient.Configure()
                             .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                             .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                             .WithCredentials(new AzureCredentials(tokenCredentials, tokenCredentials, string.Empty, AzureEnvironment.AzureGlobalCloud))
                             .WithRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), new FixedIntervalRetryStrategy(3, TimeSpan.FromMilliseconds(500))))
                             .Build();

                // Authenticate against the management layer.
                var azureManagement = Azure.Authenticate(client, string.Empty).WithSubscription(_subscriptionId);

                // Get the storage namespace for the passed in instance name.
                var storageNamespace = azureManagement.StorageAccounts.List().FirstOrDefault(n => n.Name == _instanceName);

                // If we cant find that name, throw an exception.
                if (storageNamespace == null)
                {
                    throw new InvalidOperationException($"Could not find the storage instance {_instanceName} in the subscription Id specified");
                }

                // Storage accounts use access keys - this will be used to build a connection string.
                var accessKeys = await storageNamespace.GetKeysAsync();

                // If the access keys are not found (not configured for some reason), throw an exception.
                if (accessKeys == null)
                {
                    throw new InvalidOperationException($"Could not find access keys for the storage instance {_instanceName}");
                }

                // We just default to the first key.
                var key = accessKeys[0].Value;

                // Build the connection string.
                var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_instanceName};AccountKey={key};EndpointSuffix=core.windows.net";

                // Cache the connection string off so we don't have to reauthenticate.
                if (!ConnectionStrings.ContainsKey(_instanceName))
                {
                    ConnectionStrings.TryAdd(_instanceName, connectionString);
                }

                // Return connection string.
                return(connectionString);
            }
            catch (Exception e)
            {
                _expiryTime = null;
                Logger?.LogError(e, "An exception occured during connection to Table storage");
                throw new InvalidOperationException("An exception occurred during service connection, see inner exception for more detail", e);
            }
        }
Ejemplo n.º 32
0
 public ActivateUserRequestHandler(AuthenticationContext context)
 {
     _context = context;
 }
#pragma warning disable CA1502 // TODO: Decomplexify
#pragma warning disable CA1506
        public async Task <IActionResult> Update([FromBody] DreamDaemonResponse model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.SoftShutdown == true && model.SoftRestart == true)
            {
                return(BadRequest(new ErrorMessageResponse(ErrorCode.DreamDaemonDoubleSoft)));
            }

            // alias for changing DD settings
            var current = await DatabaseContext
                          .Instances
                          .AsQueryable()
                          .Where(x => x.Id == Instance.Id)
                          .Select(x => x.DreamDaemonSettings)
                          .FirstOrDefaultAsync(cancellationToken)
                          .ConfigureAwait(false);

            if (current == default)
            {
                return(Gone());
            }

            if (model.Port.HasValue && model.Port.Value != current.Port.Value)
            {
                var verifiedPort = await portAllocator
                                   .GetAvailablePort(
                    model.Port.Value,
                    true,
                    cancellationToken)
                                   .ConfigureAwait(false);

                if (verifiedPort != model.Port)
                {
                    return(Conflict(new ErrorMessageResponse(ErrorCode.PortNotAvailable)));
                }
            }

            var userRights = (DreamDaemonRights)AuthenticationContext.GetRight(RightsType.DreamDaemon);

            bool CheckModified <T>(Expression <Func <Api.Models.Internal.DreamDaemonSettings, T> > expression, DreamDaemonRights requiredRight)
            {
                var memberSelectorExpression = (MemberExpression)expression.Body;
                var property = (PropertyInfo)memberSelectorExpression.Member;

                var newVal = property.GetValue(model);

                if (newVal == null)
                {
                    return(false);
                }
                if (!userRights.HasFlag(requiredRight) && property.GetValue(current) != newVal)
                {
                    return(true);
                }

                property.SetValue(current, newVal);
                return(false);
            }

            return(await WithComponentInstance(
                       async instance =>
            {
                var watchdog = instance.Watchdog;
                var rebootState = watchdog.RebootState;
                var oldSoftRestart = rebootState == RebootState.Restart;
                var oldSoftShutdown = rebootState == RebootState.Shutdown;

                if (CheckModified(x => x.AllowWebClient, DreamDaemonRights.SetWebClient) ||
                    CheckModified(x => x.AutoStart, DreamDaemonRights.SetAutoStart) ||
                    CheckModified(x => x.Port, DreamDaemonRights.SetPort) ||
                    CheckModified(x => x.SecurityLevel, DreamDaemonRights.SetSecurity) ||
                    (model.SoftRestart.HasValue && !AuthenticationContext.InstancePermissionSet.DreamDaemonRights.Value.HasFlag(DreamDaemonRights.SoftRestart)) ||
                    (model.SoftShutdown.HasValue && !AuthenticationContext.InstancePermissionSet.DreamDaemonRights.Value.HasFlag(DreamDaemonRights.SoftShutdown)) ||
                    CheckModified(x => x.StartupTimeout, DreamDaemonRights.SetStartupTimeout) ||
                    CheckModified(x => x.HeartbeatSeconds, DreamDaemonRights.SetHeartbeatInterval) ||
                    CheckModified(x => x.TopicRequestTimeout, DreamDaemonRights.SetTopicTimeout) ||
                    CheckModified(x => x.AdditionalParameters, DreamDaemonRights.SetAdditionalParameters))
                {
                    return Forbid();
                }

                await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

                // run this second because current may be modified by it
                await watchdog.ChangeSettings(current, cancellationToken).ConfigureAwait(false);

                if (!oldSoftRestart && model.SoftRestart == true && watchdog.Status == WatchdogStatus.Online)
                {
                    await watchdog.Restart(true, cancellationToken).ConfigureAwait(false);
                }
                else if (!oldSoftShutdown && model.SoftShutdown == true)
                {
                    await watchdog.Terminate(true, cancellationToken).ConfigureAwait(false);
                }
                else if ((oldSoftRestart && model.SoftRestart == false) || (oldSoftShutdown && model.SoftShutdown == false))
                {
                    await watchdog.ResetRebootState(cancellationToken).ConfigureAwait(false);
                }

                return await ReadImpl(current, cancellationToken).ConfigureAwait(false);
            })
                   .ConfigureAwait(false));
        }
Ejemplo n.º 34
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

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

                TokenValidationParameters = new Microsoft.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,
                    // If the app needs access to the entire organization, then add the logic
                    // of validating the Issuer here.
                    // IssuerValidator
                },
                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 = async(context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential       = new ClientCredential(clientId, appKey);
                        string signedInUserID             = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result       = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                    },
                    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));
                    },
                    SecurityTokenValidated = (context) =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        // 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));
                    },
                }
            });
        }
Ejemplo n.º 35
0
        public static HttpClient GenerateClient(IConfiguration Configuration)
        {
            string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; // Dynamics ODATA endpoint

            string token = "";

            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


            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;
                token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
                serviceClientCredentials = new TokenCredentials(token);
            }
            else 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);
                    token = result["access_token"];
                    // set the bearer token.
                    serviceClientCredentials = new TokenCredentials(token);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message + " " + _responseContent);
                }
            }
            else
            {
                throw new Exception("No configured connection to Dynamics.");
            }

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(dynamicsOdataUri);

            string Authorization = $"Bearer {token}";

            client.DefaultRequestHeaders.Add("Authorization", Authorization);
            client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            client.DefaultRequestHeaders.Add("OData-Version", "4.0");
            client.DefaultRequestHeaders.Add("Accept", "application/json");

            return(client);
        }
Ejemplo n.º 36
0
        public string GetAadAuthenticatedToken(AsAzureContext asAzureContext, SecureString password, PromptBehavior promptBehavior, string clientId, string resourceUri, Uri resourceRedirectUri)
#endif
        {
            var authUriBuilder = new UriBuilder((string)asAzureContext.Environment.Endpoints[AsAzureEnvironment.AsRolloutEndpoints.AdAuthorityBaseUrl])
            {
                Path = string.IsNullOrEmpty(asAzureContext.Account.Tenant)
                    ? "common"
                    : asAzureContext.Account.Tenant
            };

            var authenticationContext = new AuthenticationContext(
                authUriBuilder.ToString(),
                AsAzureClientSession.TokenCache);

            AuthenticationResult result = null;
            var accountType             = string.IsNullOrEmpty(asAzureContext.Account.Type) ? AsAzureAccount.AccountType.User : asAzureContext.Account.Type;

            if (password == null && accountType == AsAzureAccount.AccountType.User)
            {
                if (asAzureContext.Account.Id != null)
                {
// TODO: Remove IfDef
#if NETSTANDARD
                    result = authenticationContext.AcquireTokenAsync(
                        resourceUri,
                        clientId,
                        resourceRedirectUri,
                        new PlatformParameters(),
                        new UserIdentifier(asAzureContext.Account.Id, UserIdentifierType.OptionalDisplayableId)).Result;
#else
                    result = authenticationContext.AcquireToken(
                        resourceUri,
                        clientId,
                        resourceRedirectUri,
                        promptBehavior,
                        new UserIdentifier(asAzureContext.Account.Id, UserIdentifierType.OptionalDisplayableId));
#endif
                }
                else
                {
// TODO: Remove IfDef
#if NETSTANDARD
                    result = authenticationContext.AcquireTokenAsync(
                        resourceUri,
                        clientId,
                        resourceRedirectUri,
                        new PlatformParameters()).Result;
#else
                    result = authenticationContext.AcquireToken(
                        resourceUri,
                        clientId,
                        resourceRedirectUri,
                        promptBehavior);
#endif
                }

                asAzureContext.Account.Id       = result.UserInfo.DisplayableId;
                asAzureContext.Account.Tenant   = result.TenantId;
                asAzureContext.Account.UniqueId = result.UserInfo.UniqueId;
            }
            else
            {
                if (accountType == AsAzureAccount.AccountType.User)
                {
// TODO: Remove IfDef
#if NETSTANDARD
                    //https://stackoverflow.com/a/39393039/294804
                    //https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482
                    //https://github.com/Azure-Samples/active-directory-dotnet-deviceprofile/blob/5d5499d09c918ae837810d457822474df97600e9/DirSearcherClient/Program.cs#L206-L210
                    // Note: More robust implementation in UserTokenProvider.Netcore.cs in DoAcquireToken
                    var codeResult = authenticationContext.AcquireDeviceCodeAsync(resourceUri, clientId).Result;
                    promptAction(codeResult?.Message);
                    result = authenticationContext.AcquireTokenByDeviceCodeAsync(codeResult).Result;
#else
                    UserCredential userCredential = new UserCredential(asAzureContext.Account.Id, password);
                    result = authenticationContext.AcquireToken(resourceUri, clientId, userCredential);
#endif

                    asAzureContext.Account.Id       = result.UserInfo.DisplayableId;
                    asAzureContext.Account.Tenant   = result.TenantId;
                    asAzureContext.Account.UniqueId = result.UserInfo.UniqueId;
                }
                else if (accountType == AsAzureAccount.AccountType.ServicePrincipal)
                {
                    if (string.IsNullOrEmpty(asAzureContext.Account.CertificateThumbprint))
                    {
// TODO: Remove IfDef
#if NETSTANDARD
                        var credential = new ClientCredential(asAzureContext.Account.Id, ConversionUtilities.SecureStringToString(password));
                        result = authenticationContext.AcquireTokenAsync(resourceUri, credential).Result;
#else
                        ClientCredential credential = new ClientCredential(asAzureContext.Account.Id, password);
                        result = authenticationContext.AcquireToken(resourceUri, credential);
#endif
                    }
                    else
                    {
                        var dataStore   = new DiskDataStore();
                        var certificate = dataStore.GetCertificate(asAzureContext.Account.CertificateThumbprint);
                        if (certificate == null)
                        {
                            throw new ArgumentException(string.Format(Resources.CertificateNotFoundInStore, asAzureContext.Account.CertificateThumbprint));
                        }
// TODO: Remove IfDef
#if NETSTANDARD
                        result = authenticationContext.AcquireTokenAsync(resourceUri, new ClientAssertionCertificate(asAzureContext.Account.Id, certificate)).Result;
#else
                        result = authenticationContext.AcquireToken(resourceUri, new ClientAssertionCertificate(asAzureContext.Account.Id, certificate));
#endif
                    }
                }
            }

            return(result?.AccessToken);
        }
Ejemplo n.º 37
0
        public static bool UserCanManageAccessForSubscription(string subscriptionId, string organizationId)
        {
            bool ret = false;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));


                // Get permissions of the user on the subscription
                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/permissions?api-version={2}",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], subscriptionId, ConfigurationManager.AppSettings["ida:ARMAuthorizationPermissionsAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Actions and NotActions
                // actions  notActions
                // -------  ----------
                // {*}      {Microsoft.Authorization/*/Write, Microsoft.Authorization/*/Delete}
                // {*/read} {}

                if (response.IsSuccessStatusCode)
                {
                    string responseContent   = response.Content.ReadAsStringAsync().Result;
                    var    permissionsResult = (Json.Decode(responseContent)).value;

                    foreach (var permissions in permissionsResult)
                    {
                        bool permissionMatch = false;
                        foreach (string action in permissions.actions)
                        {
                            var actionPattern = "^" + Regex.Escape(action.ToLower()).Replace("\\*", ".*") + "$";
                            permissionMatch = Regex.IsMatch("microsoft.authorization/roleassignments/write", actionPattern);
                            if (permissionMatch)
                            {
                                break;
                            }
                        }
                        // if one of the actions match, check that the NotActions don't
                        if (permissionMatch)
                        {
                            foreach (string notAction in permissions.notActions)
                            {
                                var notActionPattern = "^" + Regex.Escape(notAction.ToLower()).Replace("\\*", ".*") + "$";
                                if (Regex.IsMatch("microsoft.authorization/roleassignments/write", notActionPattern))
                                {
                                    permissionMatch = false;
                                }
                                if (!permissionMatch)
                                {
                                    break;
                                }
                            }
                        }
                        if (permissionMatch)
                        {
                            ret = true;
                            break;
                        }
                    }
                }
            }
            catch { }

            return(ret);
        }
Ejemplo n.º 38
0
 public EntryViewModel(AuthenticationContext context, IEventAggregator ea)
 {
     Context = context;
     EventMgr = ea;
        InitCommands();
 }
Ejemplo n.º 39
0
        public static async Task <string> CallGraphAPIOnBehalfOfUser()
        {
            string accessToken                = null;
            AuthenticationResult  result      = null;
            AuthenticationContext authContext = null;
            HttpClient            httpClient  = new HttpClient();
            string custommessage              = "";

            //
            // 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, clientSecret);
            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(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

            string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value;

            authContext = new AuthenticationContext(authority, false);

            // 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(OBOWebAPIBase, clientCred, userAssertion);

                    //result = await authContext.AcquireTokenAsync(...);
                    accessToken = result.AccessToken;
                }
                catch (AdalException ex)
                {
                    if (ex.ErrorCode == "temporarily_unavailable")
                    {
                        // Transient error, OK to retry.
                        retry = true;
                        retryCount++;
                        Thread.Sleep(1000);
                    }
                }
            } while ((retry == true) && (retryCount < 1));

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

            // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do list service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Call the WebAPIOBO.
            HttpResponseMessage response = await httpClient.GetAsync(OBOWebAPIBase + "/api/WebAPIOBO");


            if (response.IsSuccessStatusCode)
            {
                // Read the response and databind to the GridView to display To Do items.
                string s = await response.Content.ReadAsStringAsync();

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                custommessage = serializer.Deserialize <string>(s);
                return(custommessage);
            }
            else
            {
                custommessage = "Unsuccessful OBO operation : " + response.ReasonPhrase;
            }
            // An unexpected error occurred calling the Graph API.  Return a null profile.
            return(null);
        }
Ejemplo n.º 40
0
 public StanowiskoController(AuthenticationContext context)
 {
     _context = context;
 }
Ejemplo n.º 41
0
 public TasksProgressController(AuthenticationContext context) => _context = context;
        public static async Task<GraphService> GetGraphClientAsync(string[] scope)
        {
            if (graphClient != null)
            {
                return graphClient;
            }

            var errorAuthenticating = false;

            try
            {
                AuthenticationContext = new AuthenticationContext(CommonAuthority, new TokenCache());

                var token = await GetAccessTokenAsync(AuthenticationContext, scope);

                if (string.IsNullOrEmpty(token))
                {
                    return null;
                }

                var tenantId = (LastTenantId ?? OutlookTenandId) + UriSchemeDelimiter;
                var serviceRoot = new Uri(ResourceBetaUrl + tenantId);

                graphClient = new GraphService(serviceRoot, async () =>
                    await GetAccessTokenAsync(AuthenticationContext, scope));
            }
            catch (AdalException ex) when (ex.ErrorCode == AdalError.AuthenticationCanceled)
            {
                // User tried closing sign-in window
                errorAuthenticating = true;
            }
            catch (AdalServiceException ex) when (ex.ErrorCode == "access_denied")
            {
                // The permission scope asked is denied for this user:
                // AADSTS65005: 
                //   Dynamic scope is invalid: scope Calendars.ReadWrite does not exist on application 00000003-0000-0000-c000-000000000000. 
                //   Request ID: ea763e39-1df1-437f-80f5-4578482e9ea1, Timestamp: 01/20/2016 11:00:05\r\n
                //   Trace ID: 4af73768-8231-490f-8840-f059b650b574\r\n
                //   Correlation ID: 40a55660-bf44-4b69-b5d0-ed2306914f52\r\n
                //   Timestamp: 2016-01-20 11:00:04Z

                // This same exception is used when logging-in with a valid O365 account,
                // and user cancels "asks for permission" dialog

                // TODO: Workarround to avoid the scope issue
                errorAuthenticating = false;
            }
            catch (Exception)
            {
                // Whatever else happens, re-sign-in
                errorAuthenticating = true;
            }

            if (errorAuthenticating)
            {
                graphClient = await GetGraphClientAsync(scope);
            }

            return graphClient;
        }
        /// <summary>
        /// GetAzureAvailableAuthenticationMethods method implementation
        /// </summary>
        private GetAvailableAuthenticationMethodsResponse GetAzureAvailableAuthenticationMethods(AuthenticationContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }
            if (string.IsNullOrEmpty(ctx.UPN))
            {
                throw new InvalidDataException("No user identity was provided.");
            }

            GetAvailableAuthenticationMethodsRequest request = new GetAvailableAuthenticationMethodsRequest()
            {
                UserPrincipalName = ctx.UPN, ContextId = ctx.ActivityId
            };
            GetAvailableAuthenticationMethodsResponse response;

            try
            {
                response = this._sasprovider.GetAvailableAuthenticationMethods(request);
            }
            catch (Exception ex)
            {
                throw new Exception("Exception calling SAS.", ex);
            }

            if (response.Result.Value != "Success")
            {
                throw new Exception(string.Format("Unexpected SAS response status code : {0}", response.Result.Value));
            }
            return(response);
        }
Ejemplo n.º 44
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = _clientId,
                ClientSecret          = _clientSecret,
                Authority             = _authority,
                PostLogoutRedirectUri = _postLogoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = async ctx =>
                    {
                        if (ctx.AuthenticationTicket.Identity is ClaimsIdentity identity)
                        {
                            if (ctx.AuthenticationTicket.Identity.Claims.Any(x => x.Type == "groups"))
                            {
                                var claims =
                                    ctx.AuthenticationTicket.Identity.Claims.Where(x => x.Type == "groups").ToList();

                                foreach (var claim in claims)
                                {
                                    identity.AddClaim(new Claim(ClaimTypes.Role, claim.Value));
                                }
                            }
                            else if (ctx.AuthenticationTicket.Identity.Claims.Any(x => x.Type == "_claim_names"))
                            {
                                var authenticationContext =
                                    new AuthenticationContext(ctx.Options.Authority);
                                var clientCredentials =
                                    new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

                                var result =
                                    await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredentials);

                                using (var httpClient = new HttpClient())
                                {
                                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {result.AccessToken}");

                                    var tenantId =
                                        ctx.AuthenticationTicket.Identity.Claims.Single(x => x.Type == "http://schemas.microsoft.com/identity/claims/tenantid").Value;
                                    var userId =
                                        ctx.AuthenticationTicket.Identity.Claims.Single(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                                    var httpResponse =
                                        await httpClient.PostAsJsonAsync(
                                            $"https://graph.microsoft.com/v1.0/{tenantId}/users/{userId}/getMemberObjects",
                                            new { SecurityEnabledOnly = false });

                                    httpResponse.EnsureSuccessStatusCode();

                                    var jsonResult =
                                        await httpResponse.Content.ReadAsAsync <dynamic>();

                                    foreach (var value in jsonResult.value)
                                    {
                                        identity.AddClaim(new Claim(ClaimTypes.Role, value.ToString()));
                                    }
                                }
                            }
                        }
                    }
                }
            });
Ejemplo n.º 45
0
        static private async Task callTimeseriesAPI()
        {
            /*
             * NuGet Packages:
             * Microsoft.IdentityModel.Clients.ActiveDirectory
             *
             * Below you find client credentials. It is the user responsibility to be compliance to Equinor WR1211 chapter 9.3.1:
             * Passwords used to access Equinor information are private and shall not be shared or handled in a way that it allows
             * unauthorized access.
             * Secure the parameters and credentials, keep them out of the source code and version control.
             */

            //This is the resource id of the Timeseries API, provided by Omnia Plant
            const string resourceId = "";

            //This is the Equinor Azure AD tenant id, provided by Omnia Plant
            const string tenant = "";

            //This is the authority host where authentication requests are served
            const string authorityHostUrl = "";

            //This is the client/application id of your client app registered in Equinor's Azure AD tenant, provided by Omnia Plant
            const string clientId = "";

            //This is the client/application secret of your client app registered in Equinor's Azure AD tenant, provided by Omnia Plant
            const string clientSecret = "";

            //This is the API version, the version is included in the URI
            const string apiVersion = "v1.0";

            //API endpoint to call
            const string apiEndpoint = "timeseries";

            //Omnia Timeseries API host, will differ depending on being beta or GA release
            const string apiHost = "https://host/timeseries";

            // Get Access Token
            var authenticationContext = new AuthenticationContext(
                $"{authorityHostUrl}/{tenant}",
                TokenCache.DefaultShared);


            // Get Calling User's Access Token (Native Client)
            //AuthenticationResult token = await authenticationContext.AcquireTokenAsync(resourceId,
            //                 clientId, new Uri($"{redirectUri}"),
            //                 new PlatformParameters(PromptBehavior.Auto));

            // Get Access Token from API Client/Secret  (Web)
            AuthenticationResult token = await authenticationContext.AcquireTokenAsync(
                resource : resourceId,
                clientCredential : new ClientCredential(
                    clientId: clientId,
                    clientSecret: clientSecret));

            string bearerToken = token.CreateAuthorizationHeader();

            // Get Timeseries Metadata object by ID
            var client = new HttpClient();

            // Request headers
            client.DefaultRequestHeaders.Add("Authorization", bearerToken);

            // ID of the Timeseries Metadata object to get
            string id = "guid";

            var myUri    = $"{apiHost}/{apiVersion}/{apiEndpoint}/{id}";
            var response = await client.GetAsync(myUri);

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

            Console.WriteLine(json);
        }
Ejemplo n.º 46
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            //// calculate something for us to return
            //int length = (activity.Text ?? string.Empty).Length;

            //// return our reply to the user
            //await context.PostAsync($"You sent {activity.Text} which was {length} characters");

            if (activity.Text == "login")
            {
                // create state (passing data) for OAuth
                var convRef  = context.Activity.ToConversationReference();
                var stateCol = System.Web.HttpUtility.ParseQueryString(string.Empty);
                stateCol["userId"]         = convRef.User.Id;
                stateCol["botId"]          = convRef.Bot.Id;
                stateCol["conversationId"] = convRef.Conversation.Id;
                stateCol["serviceUrl"]     = convRef.ServiceUrl;
                stateCol["channelId"]      = convRef.ChannelId;

                //var uriBuilder = new UriBuilder(ConfigurationManager.AppSettings["OAuthCallbackUrl"]);
                //var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
                //query["userId"] = convRef.User.Id;
                //query["botId"] = convRef.Bot.Id;
                //query["conversationId"] = convRef.Conversation.Id;
                //query["serviceUrl"] = convRef.ServiceUrl;
                //query["channelId"] = convRef.ChannelId;
                //uriBuilder.Query = query.ToString();
                //var redirectUrl = uriBuilder.ToString();

                // create Azure AD signin context
                var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
                var authUri     = authContext.GetAuthorizationRequestUrlAsync(
                    "https://outlook.office365.com/",
                    ConfigurationManager.AppSettings["ClientId"],
                    new Uri(ConfigurationManager.AppSettings["OAuthCallbackUrl"]),
                    UserIdentifier.AnyUser,
                    "&state=" + System.Web.HttpUtility.UrlEncode(stateCol.ToString()));

                // show SignIn card (setting oauth sign-in url to SignIn card)
                var reply = context.MakeMessage();
                reply.Text = "Authentication Required";
                reply.Attachments.Add(SigninCard.Create(
                                          "Login",
                                          "Please login to Office 365",
                                          authUri.Result.ToString()).ToAttachment());
                await context.PostAsync(reply);
            }
            else if (activity.Text == "get mail")
            {
                string accessToken = string.Empty;

                using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    var dataStore = scope.Resolve <IBotDataStore <BotData> >();
                    var convRef   = context.Activity.ToConversationReference();
                    var address   = new Microsoft.Bot.Builder.Dialogs.Address
                                    (
                        botId: convRef.Bot.Id,
                        channelId: convRef.ChannelId,
                        userId: convRef.User.Id,
                        conversationId: convRef.Conversation.Id,
                        serviceUrl: convRef.ServiceUrl
                                    );
                    var userData = await dataStore.LoadAsync(
                        address,
                        BotStoreType.BotUserData,
                        CancellationToken.None);

                    accessToken = userData.GetProperty <string>("AccessToken");
                }

                if (string.IsNullOrEmpty(accessToken))
                {
                    await context.PostAsync("Not logging-in (type \"login\")");
                }
                else
                {
                    // Get recent 10 e-mail from Office 365
                    HttpClient cl           = new HttpClient();
                    var        acceptHeader =
                        new MediaTypeWithQualityHeaderValue("application/json");
                    cl.DefaultRequestHeaders.Accept.Add(acceptHeader);
                    cl.DefaultRequestHeaders.Authorization
                        = new AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage httpRes =
                        await cl.GetAsync("https://outlook.office365.com/api/v1.0/me/messages?$orderby=DateTimeSent%20desc&$top=10&$select=Subject,From");

                    if (httpRes.IsSuccessStatusCode)
                    {
                        var     strRes = httpRes.Content.ReadAsStringAsync().Result;
                        JObject jRes   = await httpRes.Content.ReadAsAsync <JObject>();

                        JArray jValue = (JArray)jRes["value"];
                        foreach (JObject jItem in jValue)
                        {
                            string sub = $"Subject={((JValue)jItem["Subject"]).Value}";
                            sub = sub.Replace('<', ' ').Replace('>', ' ').Replace('[', ' ').Replace(']', ' ');
                            await context.PostAsync(sub);
                        }
                    }
                    else
                    {
                        await context.PostAsync("Failed to get e-mail.\n\nPlease type \"login\" before you get e-mail.");
                    }
                }
            }
            else if (activity.Text == "revoke")
            {
                await context.PostAsync("Click [here](https://account.activedirectory.windowsazure.com/), login, and remove this app (Bot with Office 365 Authentication Example).");
            }
            else if (activity.Text == "login_succeed")
            {
                await context.PostAsync("You logged in !");
            }
            else
            {
                await context.PostAsync("# Bot Help\n\nType the following command. (You need your Office 365 Exchange Online subscription.)\n\n**login** -- Login to Office 365\n\n**get mail** -- Get your e-mail from Office 365\n\n**revoke** -- Revoke permissions for accessing your e-mail");
            }

            context.Wait(MessageReceivedAsync);
        }
Ejemplo n.º 47
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
 }
        protected async Task <bool> InvokeActionAsync(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            FilterInfo       filterInfo       = GetFilters(controllerContext, actionDescriptor);
            ExceptionContext exceptionContext = null;

            try
            {
                AuthenticationContext authenticationContext = InvokeAuthenticationFilters(controllerContext,
                                                                                          filterInfo.AuthenticationFilters, actionDescriptor);
                if (authenticationContext.Result != null)
                {
                    // An authentication filter signaled that we should short-circuit the request. Let all
                    // authentication filters contribute to an action result (to combine authentication
                    // challenges). Then, run this action result.
                    AuthenticationChallengeContext challengeContext =
                        InvokeAuthenticationFiltersChallenge(controllerContext,
                                                             filterInfo.AuthenticationFilters, actionDescriptor, authenticationContext.Result);
                    await InvokeActionResultAsync(controllerContext,
                                                  challengeContext.Result ?? authenticationContext.Result).ConfigureAwait(false);
                }
                else
                {
                    AuthorizationContext authorizationContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);
                    if (authorizationContext.Result != null)
                    {
                        // An authorization filter signaled that we should short-circuit the request. Let all
                        // authentication filters contribute to an action result (to combine authentication
                        // challenges). Then, run this action result.
                        AuthenticationChallengeContext challengeContext =
                            InvokeAuthenticationFiltersChallenge(controllerContext,
                                                                 filterInfo.AuthenticationFilters, actionDescriptor, authorizationContext.Result);
                        await InvokeActionResultAsync(controllerContext,
                                                      challengeContext.Result ?? authorizationContext.Result).ConfigureAwait(false);
                    }
                    else
                    {
                        if (controllerContext.Controller.ValidateRequest)
                        {
                            ValidateRequest(controllerContext);
                        }

                        IDictionary <string, object> parameters        = GetParameterValues(controllerContext, actionDescriptor);
                        ActionExecutedContext        postActionContext =
                            await Task <ActionExecutedContext> .Factory.FromAsync(
                                delegate(AsyncCallback asyncCallback, object asyncState)
                        {
                            return(BeginInvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters, asyncCallback, asyncState));
                        },
                                EndInvokeActionMethodWithFilters,
                                null);

                        // The action succeeded. Let all authentication filters contribute to an action
                        // result (to combine authentication challenges; some authentication filters need
                        // to do negotiation even on a successful result). Then, run this action result.
                        AuthenticationChallengeContext challengeContext =
                            InvokeAuthenticationFiltersChallenge(controllerContext,
                                                                 filterInfo.AuthenticationFilters, actionDescriptor,
                                                                 postActionContext.Result);
                        await InvokeActionResultWithFiltersAsync(controllerContext, filterInfo.ResultFilters,
                                                                 challengeContext.Result ?? postActionContext.Result).ConfigureAwait(false);
                    }
                }
            }
            catch (ThreadAbortException)
            {
                // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
                // the filters don't see this as an error.
                throw;
            }
            catch (Exception ex)
            {
                // something blew up, so execute the exception filters
                exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);
                if (!exceptionContext.ExceptionHandled)
                {
                    throw;
                }
            }
            if (exceptionContext != null)
            {
                await InvokeActionResultAsync(controllerContext, exceptionContext.Result).ConfigureAwait(false);
            }
            return(true);
        }
Ejemplo n.º 49
0
 public void OnAuthentication(AuthenticationContext filterContext)
 {
     throw new NotImplementedException();
 }
    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);
    }
Ejemplo n.º 51
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(AadDeviceCodeAccessToken));

            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));

            CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out string serverUrl);
            ArgUtil.NotNullOrEmpty(serverUrl, nameof(serverUrl));

            var tenantAuthorityUrl = GetTenantAuthorityUrl(context, serverUrl);

            if (tenantAuthorityUrl == null)
            {
                throw new NotSupportedException($"This Azure DevOps organization '{serverUrl}' is not backed by Azure Active Directory.");
            }

            LoggerCallbackHandler.LogCallback = ((LogLevel level, string message, bool containsPii) =>
            {
                switch (level)
                {
                case LogLevel.Information:
                    trace.Info(message);
                    break;

                case LogLevel.Error:
                    trace.Error(message);
                    break;

                case LogLevel.Warning:
                    trace.Warning(message);
                    break;

                default:
                    trace.Verbose(message);
                    break;
                }
            });

            LoggerCallbackHandler.UseDefaultLogging = false;
            AuthenticationContext ctx   = new AuthenticationContext(tenantAuthorityUrl.AbsoluteUri);
            var queryParameters         = $"redirect_uri={Uri.EscapeDataString(new Uri(serverUrl).GetLeftPart(UriPartial.Authority))}";
            DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync("https://management.core.windows.net/", _azureDevOpsClientId, queryParameters).GetAwaiter().GetResult();

            var term = context.GetService <ITerminal>();

            term.WriteLine($"Please finish AAD device code flow in browser ({codeResult.VerificationUrl}), user code: {codeResult.UserCode}");
            if (string.Equals(CredentialData.Data[Constants.Agent.CommandLine.Flags.LaunchBrowser], bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
#if OS_WINDOWS
                    Process.Start(new ProcessStartInfo()
                    {
                        FileName = codeResult.VerificationUrl, UseShellExecute = true
                    });
#elif OS_LINUX
                    Process.Start(new ProcessStartInfo()
                    {
                        FileName = "xdg-open", Arguments = codeResult.VerificationUrl
                    });
#else
                    Process.Start(new ProcessStartInfo()
                    {
                        FileName = "open", Arguments = codeResult.VerificationUrl
                    });
#endif
                }
                catch (Exception ex)
                {
                    // not able to open browser, ex: xdg-open/open is not installed.
                    trace.Error(ex);
                    term.WriteLine($"Fail to open browser. {codeResult.Message}");
                }
            }

            AuthenticationResult authResult = ctx.AcquireTokenByDeviceCodeAsync(codeResult).GetAwaiter().GetResult();
            ArgUtil.NotNull(authResult, nameof(authResult));
            trace.Info($"receive AAD auth result with {authResult.AccessTokenType} token");

            var            aadCred = new VssAadCredential(new VssAadToken(authResult));
            VssCredentials creds   = new VssCredentials(null, aadCred, CredentialPromptType.DoNotPrompt);
            trace.Info("cred created");

            return(creds);
        }
 public UserApplicationRepository(AuthenticationContext _context) : base(_context)
 {
 }
 public bool Validate(AuthenticationContext context)
 {
     return true;
 }
        public void ConfigureAuth(IAppBuilder app)
        {
            string clientId        = ConfigurationManager.AppSettings["ida:ClientID"];
            string appKey          = ConfigurationManager.AppSettings["ida:Password"];
            string graphResourceID = "https://graph.windows.net";
            //fixed address for multitenant apps in the public cloud
            string Authority = "https://login.windows.net/common/";

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = clientId,
                Authority = 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()
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;

                        ClientCredential credential = new ClientCredential(clientId, 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("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
                        AuthenticationResult result       = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, 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));
                    },
                    // 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));
                    }
                }
            });
        }
Ejemplo n.º 55
0
 public DepositController(IConfiguration configuration, AuthenticationContext db)
 {
     Configuration = configuration;
     _db           = db;
 }
Ejemplo n.º 56
0
        public static bool ServicePrincipalHasReadAccessToSubscription(string subscriptionId, string organizationId)
        {
            bool ret = false;

            try
            {
                // Aquire App Only Access Token to call Azure Resource Manager - Client Credential OAuth Flow
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId));
                AuthenticationResult  result      = authContext.AcquireToken(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential);


                // Get permissions of the app on the subscription
                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/permissions?api-version={2}",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], subscriptionId, ConfigurationManager.AppSettings["ida:ARMAuthorizationPermissionsAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Actions and NotActions
                // actions  notActions
                // -------  ----------
                // {*}      {Microsoft.Authorization/*/Write, Microsoft.Authorization/*/Delete}
                // {*/read} {}

                if (response.IsSuccessStatusCode)
                {
                    string responseContent   = response.Content.ReadAsStringAsync().Result;
                    var    permissionsResult = (Json.Decode(responseContent)).value;

                    foreach (var permissions in permissionsResult)
                    {
                        bool permissionMatch = false;
                        foreach (string action in permissions.actions)
                        {
                            if (action.Equals("*/read", StringComparison.CurrentCultureIgnoreCase) || action.Equals("*", StringComparison.CurrentCultureIgnoreCase))
                            {
                                permissionMatch = true;
                                break;
                            }
                        }
                        // if one of the actions match, check that the NotActions don't
                        if (permissionMatch)
                        {
                            foreach (string notAction in permissions.notActions)
                            {
                                if (notAction.Equals("*", StringComparison.CurrentCultureIgnoreCase) || notAction.EndsWith("/read", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    permissionMatch = false;
                                    break;
                                }
                            }
                        }
                        if (permissionMatch)
                        {
                            ret = true;
                            break;
                        }
                    }
                }
            }
            catch { }

            return(ret);
        }
        /// <summary>
        /// GetAuthenticationMethods method implmentation
        /// </summary>
        public override List <AvailableAuthenticationMethod> GetAuthenticationMethods(AuthenticationContext ctx)
        {
            if (!IsInitialized)
            {
                throw new Exception("Provider not initialized !");
            }

            List <AvailableAuthenticationMethod> result = GetSessionData(this.Kind, ctx);

            if (result != null)
            {
                return(result);
            }
            else
            {
                result = new List <AvailableAuthenticationMethod>();
                GetAvailableAuthenticationMethodsResponse authMethods = GetAzureAvailableAuthenticationMethods(ctx);

                foreach (AuthenticationMethod current in authMethods.AuthenticationMethods)
                {
                    AvailableAuthenticationMethod item = GetAuthenticationMethodProperties(current);
                    if (item.Method != AuthenticationResponseKind.Error)
                    {
                        item.IsDefault = current.IsDefault;
                        result.Add(item);
                    }
                }
                if (result.Count > 0)
                {
                    SaveSessionData(this.Kind, ctx, result);
                }
            }
            return(result);
        }
        //
        // This method will be invoked as a call-back from an authentication service (e.g., https://login.windows.net/).
        // It is not intended to be called directly, or to be called without first invoking the "GetAuthorizationUrl" method.
        // On completion, the method will cache the refresh token and access tokens, and redirect to the URL
        //     specified in the state cookie (created by the "GetAuthorizationUrl" method, with its unique ID
        //     included in the "state" of this method).
        //
        public ActionResult Index(string code, string error, string error_description, string resource, string state)
        {
            resource = GetFromCache("Resource").ToString();

            // NOTE: In production, OAuth must be done over a secure HTTPS connection.

            if (Request.Url.Scheme != "https" && !Request.Url.IsLoopback)
            {
                HandleErrorInfo errorViewModel = new HandleErrorInfo(new Exception("OAuth must use HTTPS"), "OAuth", "Index");
                return(View("Error", errorViewModel));
            }


            // Ensure there is a state value on the response.  If there is none, stop OAuth processing and display an error.

            if (state == null)
            {
                HandleErrorInfo errorViewModel = new HandleErrorInfo(new Exception("Anti-Forgery state value not found"), "OAuth", "Index");
                return(View("Error", errorViewModel));
            }


            // Ensure the saved state value matches the value from the response.  If it does not, stop OAuth processing and display an error.

            if (!FindOAuthStateInCache(state))
            {
                RemoveOAuthStateFromCache(state);
                HandleErrorInfo errorViewModel = new HandleErrorInfo(new Exception("Anti-Forgery state failed validation"), "OAuth", "Index");
                return(View("Error", errorViewModel));
            }

            RemoveOAuthStateFromCache(state);


            // Handle errors from the OAuth response, if any.  If there are errors, stop OAuth processing and display an error.

            if (error != null)
            {
                HandleErrorInfo errorViewModel = new HandleErrorInfo(new Exception(error), "OAuth", "Index");
                return(View("Error", errorViewModel));
            }


            // Redeem the authorization code from the response for an access token and refresh token.

            try
            {
                ClientCredential      credential  = new ClientCredential(clientId, appKey);
                string                authority   = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
                AuthenticationContext authContext = new AuthenticationContext(authority);
                AuthenticationResult  result      = authContext.AcquireTokenByAuthorizationCode(
                    code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential);

                // Cache the access token and refresh token
                SaveAccessTokenInCache(resource, result.AccessToken, (result.ExpiresOn.AddMinutes(-5)).ToString());
                SaveRefreshTokenInCache(result.RefreshToken);

                // Also save the Tenant ID for later use when calling the Graph API.
                SaveInCache("TenantId", result.TenantId);

                // Return to the originating page where the user triggered the sign-in
                Uri redirectTo = (Uri)GetFromCache("RedirectTo");
                return(Redirect(redirectTo.ToString()));
            }
            catch (Exception x)
            {
                HandleErrorInfo errorViewModel = new HandleErrorInfo(x, "OAuth", "Index");
                return(View("Error", errorViewModel));
            }
        }
        /// <summary>
        /// Used to get the HTTP authorization header
        /// </summary>
        /// <returns>Returned a string value containing the auth text value</returns>
        private string GetAuthorizationHeader()
        {
            string authzHeader = null;

            try
            {
                var context = new AuthenticationContext(Properties.FullTenantAddress);
                var credential = new SymmetricKeyCredential(Properties.IssuingResource, Convert.FromBase64String(Properties.SymmetricKey));
                var token = context.AcquireToken(Properties.ServiceRealm, credential);
                authzHeader = token.CreateAuthorizationHeader();
            }
            catch (Exception ex)
            {
                var aex = ex as AALException;
                throw new ApplicationException(aex.Message);
            }

            return authzHeader;
        }