private async Task InitOneNoteRestConnection() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover onenote endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // authenticate with directory service
      var discoClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);
          return authResult.AccessToken;
        });

      // query discovery service for endpoint for onenote endpoint
      var discoCapabilityResult = await discoClient.DiscoverCapabilityAsync("Notes");

      // get details around onedrive endpoint (replace 1.0 with 2.0 for the new REST API)
      _oneNoteResourceId = discoCapabilityResult.ServiceResourceId;
      _oneNoteEndpoint = discoCapabilityResult.ServiceEndpointUri.ToString();
      var accessToken = (await authContext.AcquireTokenSilentAsync(_oneNoteResourceId, clientCredential, userIdentifier)).AccessToken;

      // set the access token on all requests for onenote API
      _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

      return;
    }
        private static async Task<SharePointClient> GetSharePointClient()
        {
            string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

            CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability);
            SharePointClient client = new SharePointClient(capability.ServiceEndpointUri,
                async () =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return authResult.AccessToken;
                });
            return client;
        }
    // GET: Discovery
    public async Task<ActionResult> Index()
    {
      // get instance of the authentication context using the token cache we created previously
      var signedInUser = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signedInUser));

      // create credentials for the application
      var appCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

      // get user identifier
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
      var userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create instance of DiscoveryClient
      var discoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () =>
        {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, appCred, userId);
          return authResult.AccessToken;
        });

      // query discovery service for endpoints
      var capabilitiesResults = await discoveryClient.DiscoverCapabilitiesAsync();

      return View(capabilitiesResults);
    }
  /// <summary>
  /// Checks that an OutlookServicesClient object is available. 
  /// </summary>
  /// <returns>The OutlookServicesClient object. </returns>
  public static async Task<OutlookServicesClient> EnsureClientCreated() {
    AuthenticationContext = new AuthenticationContext(CommonAuthority);

    if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) {
      // Bind the AuthenticationContext to the authority that sourced the token in the cache 
      // this is needed for the cache to work when asking for a token from that authority 
      // (the common endpoint never triggers cache hits) 
      string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority;
      AuthenticationContext = new AuthenticationContext(cachedAuthority);

    }

    // Create a DiscoveryClient using the discovery endpoint Uri.  
    DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri,
        async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId));

    // Now get the capability that you are interested in.
    var result = await discovery.DiscoverCapabilityAsync("Mail");

    var client = new OutlookServicesClient(
        result.ServiceEndpointUri,
        async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId));

    return client;
  }
        private async void btnGetMyFiles_Click(object sender, RoutedEventArgs e)
        {
            Files.Clear();

            DiscoveryClient discoveryClient = new DiscoveryClient(
                    async ()=>
                    {
                        var authResult = await AuthenticationHelper.GetAccessToken(AuthenticationHelper.DiscoveryServiceResourceId);

                        return authResult.AccessToken;
                    }
                );

            var appCapabilities = await discoveryClient.DiscoverCapabilitiesAsync();

            var myFilesCapability = appCapabilities
                                    .Where(s => s.Key == "MyFiles")
                                    .Select(p=>new {Key=p.Key, ServiceResourceId=p.Value.ServiceResourceId, ServiceEndPointUri=p.Value.ServiceEndpointUri})
                                    .FirstOrDefault();
                                    
            
            if(myFilesCapability != null)
            {
                SharePointClient myFilesClient = new SharePointClient(myFilesCapability.ServiceEndPointUri,
                    async()=>
                    {
                        var authResult = await AuthenticationHelper.GetAccessToken(myFilesCapability.ServiceResourceId);

                        return authResult.AccessToken;
                    });

                var myFilesResult = await myFilesClient.Files.ExecuteAsync();

                do
                {
                    var myFiles = myFilesResult.CurrentPage;
                    foreach (var myFile in myFiles)
                    {
                        Files.Add(new MyFile { Name = myFile.Name });
                    }

                    myFilesResult = await myFilesResult.GetNextPageAsync();

                } while (myFilesResult != null);

                if(Files.Count == 0)
                {
                    Files.Add(new MyFile { Name = "No files to display!" });
                }

                

            }
            else
            {
                MessageDialog dialog = new MessageDialog(string.Format("This Windows app does not have access to users' files. Please contact your administrator."));
                await dialog.ShowAsync();
            }
           
        }
Example #6
0
 static void Main(string[] args)
 {
     using (var client = new DiscoveryClient())
     {
         client.ServiceOperation();
     }
 }
    private async Task<OutlookServicesClient> EnsureClientCreated() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover contact endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // create O365 discovery client 
      DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);

          return authResult.AccessToken;
        });

      // query discovery service for endpoint for 'calendar' endpoint
      CapabilityDiscoveryResult dcr = await discovery.DiscoverCapabilityAsync("Contacts");

      // create an OutlookServicesclient
      return new OutlookServicesClient(dcr.ServiceEndpointUri,
        async () => {
          var authResult =
            await
              authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential, userIdentifier);
          return authResult.AccessToken;
        });
    }
        // GET: MyFiles
        public async Task<ActionResult> Index()
        {
            List<MyFile> myFiles = new List<MyFile>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(AADAppSettings.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(AADAppSettings.DiscoveryServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("MyFiles");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                SharePointClient spClient = new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var filesResult = await spClient.Files.ExecuteAsync();

                do
                {
                    var files = filesResult.CurrentPage.OfType<File>();

                    foreach (var file in files)
                    {
                        myFiles.Add(new MyFile { Name = file.Name });
                    }

                    filesResult = await filesResult.GetNextPageAsync();

                } while (filesResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(myFiles);
        }
        // GET: Contacts
        public async Task<ActionResult> Index()
        {

            List<MyContact> myContacts = new List<MyContact>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("Contacts");

                OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var contactsResult = await exClient.Me.Contacts.ExecuteAsync();

                do
                {
                    var contacts = contactsResult.CurrentPage;
                    foreach (var contact in contacts)
                    {
                        myContacts.Add(new MyContact { Name = contact.DisplayName });
                    }

                    contactsResult = await contactsResult.GetNextPageAsync();

                } while (contactsResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    //handle token acquisition failure
                }
            }


            return View(myContacts);
        }
Example #10
0
        // GET: User
        //public ActionResult Index()
        //{
        // return View();
        //}

        internal static async Task<SharePointClient> EnsureSharePointClientCreatedAsync()
        {
            string _clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string _clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];

            string _tenantId = ConfigurationManager.AppSettings["ida:TenantID"];
            string _aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string _authority = _aadInstance + _tenantId;

            string _discoverySvcEndpointUriStr = "https://api.office.com/discovery/v1.0/me/";
            Uri _discoverySvcEndpointUri = new Uri(_discoverySvcEndpointUriStr);
            string _discoverySvcResourceId = "https://api.office.com/discovery/";


            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            AuthenticationContext authContext = new AuthenticationContext(_authority, new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(_discoverySvcEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(_discoverySvcResourceId,
                                                                                   new ClientCredential(_clientId,
                                                                                                        _clientSecret),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));
                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("MyFiles");

                return new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                                                                                   new ClientCredential(_clientId,
                                                                                                        _clientSecret),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Partially handle token acquisition failure here and bubble it up to the controller
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
 private async Task getAppCapabilities()
 {
     DiscoveryClient discoveryClient = new DiscoveryClient(
             async () =>
             {
                 var authResult = await AuthenticationHelper.GetAccessToken(AuthenticationHelper.DiscoveryServiceResourceId);
                 return authResult.AccessToken;
             }
         );
     AppCapabilities = await discoveryClient.DiscoverCapabilitiesAsync();
 }
        public async Task<ActionResult> Sites()
        {
            List<SearchResult> results = new List<SearchResult>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResultDisc = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResultDisc.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("RootSite");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                var authResultSharePoint = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, 
                    new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                var sharePointToken = authResultSharePoint.AccessToken;

                results.Add(new SearchResult
                {
                    Title = "Root Site",
                    Path = dcr.ServiceResourceId,
                });

                var query = "/search/query?querytext='contentclass:sts_site'&trimduplicates=true&rowlimit=50&SelectProperties='WebTemplate,Title,Path,SiteLogo,contentclass'";

                await ExecuteSearchQuery(results, dcr, sharePointToken, query);

            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(results);
        }
Example #13
0
        private static async Task<SharePointClient> EnsureClient()
        {
            DiscoveryClient discoveryClient = new DiscoveryClient(
                    async () => await GetAccessTokenForResource("https://api.office.com/discovery/"));

            // Get the "MyFiles" capability.
            CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync("MyFiles");
            
            return new SharePointClient(result.ServiceEndpointUri, async () => {
                return await GetAccessTokenForResource(result.ServiceResourceId);
            });
        }
        internal static async Task<SharePointClient> EnsureSharePointClientCreatedAsync(string capabilityName)
        {
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            //pay attention to the ADALTokenCache in this example
            AuthenticationContext authContext = new AuthenticationContext(
                Constants.Authority, new ADALTokenCache(signInUserId));

            try
            {
                //The discovery client gives us the discovery URL
                DiscoveryClient discClient = new DiscoveryClient(new Uri(Constants.DiscoveryServiceEndpointUri),
                    async () =>
                    {
                        var authResult =
                            await authContext.AcquireTokenSilentAsync(Constants.DiscoveryServiceResourceId,
                            new ClientCredential(Constants.ClientId,
                            Constants.ClientSecret),
                            new UserIdentifier(userObjectId,
                            UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);

                //We can now create a SharePointClient
                return new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(
                            dcr.ServiceResourceId,
                            new ClientCredential(Constants.ClientId,Constants.ClientSecret),
                            new UserIdentifier(userObjectId,UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Partially handle token acquisition failure here and bubble it up to the controller
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
        internal static async Task<OutlookServicesClient> EnsureOutlookServicesClientCreatedAsync(string capabilityName)
        {

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new NaiveSessionCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);

                return new OutlookServicesClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
        internal static async Task<SharePointClient> EnsureSharePointClientCreatedAsync(string capabilityName)
        {

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // !!! NOTE: DO NOT USE NaiveSessionCache IN PRODUCTION. A MORE PERSISTENT CACHE SUCH AS A DATABASE IS RECOMMENDED FOR PRODUCTION USE !!!!
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new NaiveSessionCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));
                        return authResult.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync(capabilityName);

                return new SharePointClient(dcr.ServiceEndpointUri,
                    async () =>
                    {
                        var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                                                                                   new ClientCredential(SettingsHelper.ClientId,
                                                                                                        SettingsHelper.AppKey),
                                                                                   new UserIdentifier(userObjectId,
                                                                                                      UserIdentifierType.UniqueId));

                        return authResult.AccessToken;
                    });
            }
            catch (AdalException exception)
            {
                //Partially handle token acquisition failure here and bubble it up to the controller
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
        public static async Task<DiscoveryClient> GetDiscoveryClient(string capability)
        {
            var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimsObjectIdentifier).Value;
            var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
            var authContext = GetAuthContext();

            _DiscoveryClient = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
                async () =>
                {
                    return await GetAccessToken(SettingsHelper.O365DiscoveryResourceId);
                });

            var dcr = await _DiscoveryClient.DiscoverCapabilityAsync(capability);

            return _DiscoveryClient;
        }
Example #18
0
      private async void Form1_Load( object sender, EventArgs e )
      {

         DiscoveryClient discoveryClient = new DiscoveryClient( () =>
         {
            var result = Program.authContext.AcquireToken( "https://api.office.com/discovery/", SiteSettings.ClientId, new Uri( SiteSettings.RedirectUrl ) );
            return result.AccessToken;
         } );
         var capabilities = await discoveryClient.DiscoverCapabilitiesAsync();
         var fileSources = new[]
                           {
                                 "MyFiles",
                                 "RootSite"
                           };
         DataTable dt = new DataTable( "Capabilites" );
         dt.Columns.Add( "Name", typeof( string ) );
         dt.Columns.Add( "CapabilityResult", typeof( CapabilityDiscoveryResult ) );

         dt.Rows.Add( "<Select a Resource>", null );
         dt.Rows.Add(
               "GraphApi",
               new CapabilityDiscoveryResult( new Uri( SiteSettings.GraphApiEndpoint.Trim( '/' ) ), SiteSettings.GraphResourceId ) );
         foreach ( var capability in capabilities.Where( c => fileSources.Contains( c.Key ) ) )
         {
            if ( capability.Key == "RootSite" )
            {
               var sharePointItem = new KeyValuePair<string, CapabilityDiscoveryResult>( "SharePoint", capability.Value );
               dt.Rows.Add( sharePointItem.Key, sharePointItem.Value );
            }
            else if ( capability.Key == "MyFiles" )
            {
               var oneDriveItem = new KeyValuePair<string, CapabilityDiscoveryResult>( "OneDrive", capability.Value );
               dt.Rows.Add( oneDriveItem.Key, oneDriveItem.Value );
            }
            else
               dt.Rows.Add( capability.Key, capability.Value );
         }
         comboBox1.DisplayMember = "Name";
         comboBox1.ValueMember = "CapabilityResult";

         comboBox1.DataSource = dt;

      }
        // GET: api/DiscoveryResource
        public async Task<IEnumerable<DiscoveryResources>> Get()
        {
            ClientCredential clientCred = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);
            var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
            string userAccessToken = bootstrapContext.Token;
            UserAssertion userAssertion = new UserAssertion(userAccessToken);

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, SettingsHelper.Tenant));

            DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    () =>
                    {
                        var authResult = authContext.AcquireToken(SettingsHelper.DiscoveryServiceResourceId, clientCred, userAssertion);
                        return authResult.AccessToken;
                    });

            var dcr = await discClient.DiscoverCapabilitiesAsync();
            IEnumerable<DiscoveryResources> appCapabilities = dcr.Select(p => new DiscoveryResources { CapabilityName = p.Key, ServiceEndpointUri = p.Value.ServiceEndpointUri.ToString(), ServiceResourceId = p.Value.ServiceResourceId });
            return appCapabilities;
        }
Example #20
0
        public DiscoveryHelper(AuthenticationHelper authenticationHelper) : 
            base(authenticationHelper)
        {
            DiscoveryClient discoveryClient =
                new DiscoveryClient(
                    Office365ServicesUris.DiscoveryServiceEndpointUri,
                                    async () =>
                                    {
                                        var discoveryAuthResult =
                                            await this.AuthenticationHelper.AuthenticationContext.AcquireTokenSilentAsync(
                                                Office365ServicesUris.DiscoveryServiceResourceId,
                                                AuthenticationHelper.ClientId,
                                                new UserIdentifier(
                                                    this.AuthenticationHelper.AuthenticationResult.UserInfo.UniqueId, 
                                                    UserIdentifierType.UniqueId));

                                        return discoveryAuthResult.AccessToken;
                                    });

            this.DiscoveryClient = discoveryClient;
        }
    // GET: Calendar
    public async Task<ActionResult> Index() {
      // fetch from stuff user claims
      var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
      var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;

      // discover contact endpoint
      var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
      var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

      // create auth context
      AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EFADALTokenCache(signInUserId));

      // create O365 discovery client 
      DiscoveryClient discovery = new DiscoveryClient(new Uri(SettingsHelper.O365DiscoveryServiceEndpoint),
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365DiscoveryResourceId, clientCredential, userIdentifier);

          return authResult.AccessToken;
        });

      // query discovery service for endpoint for 'calendar' endpoint
      var dcr = await discovery.DiscoverCapabilityAsync("Calendar");

      // create Outlook client using the calendar api endpoint
      OutlookServicesClient client = new OutlookServicesClient(dcr.ServiceEndpointUri,
        async () => {
          var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, clientCredential,
          userIdentifier);

          return authResult.AccessToken;
        });

      // get contacts
      var results = await client.Me.Events.Take(20).ExecuteAsync();
      ViewBag.Events = results.CurrentPage.OrderBy(c => c.Start);

      return View();
    }
Example #22
0
        public async Task <ActionResult> Login([FromBody] JObject jCredentials)
        {
            try
            {
                _logger.LogInformation("Login() called from: " + HttpContext.Connection.RemoteIpAddress.ToString());

                var received = new { Username = string.Empty, Password = string.Empty };

                received = JsonConvert.DeserializeAnonymousType(jCredentials.ToString(Formatting.None), received);

                _logger.LogInformation($"Paramerters: {received.Username}");

                var disco = await DiscoveryClient.GetAsync(Configuration["TokenAuthService"]);

                if (disco.IsError)
                {
                    _logger.LogError($"Failed to detect identity server");

                    return(new JsonResult(new
                    {
                        respcode = ResponseCodes.SystemError,
                        description = ResponseCodes.SystemError.DisplayName(),
                        token = string.Empty,
                        roles = string.Empty
                    }));
                }

                var tokenClient = new TokenClient(disco.TokenEndpoint, Configuration["APIClientId"], Configuration["ClientSecret"]);

                var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(received.Username, received.Password);

                if (tokenResponse.IsError)
                {
                    _logger.LogError($"Error in getting auth token: {tokenResponse.Error}: {tokenResponse.ErrorDescription}, {tokenResponse.Exception?.Message}");
                    return(new JsonResult(new
                    {
                        respcode = ResponseCodes.AuthenticationFailed,
                        description = ResponseCodes.AuthenticationFailed.DisplayName(),
                        token = string.Empty,
                        roles = string.Empty
                    }));
                }

                _logger.LogInformation($"Returning token: {tokenResponse.AccessToken}");
                return(new JsonResult(new
                {
                    respcode = ResponseCodes.Successful,
                    description = ResponseCodes.Successful.DisplayName(),
                    token = tokenResponse.AccessToken
                }));
            }
            catch (Exception e)
            {
                _logger.LogError($"Generic exception handler invoked. {e.Message}: {e.StackTrace}");

                return(new JsonResult(new
                {
                    respcode = ResponseCodes.SystemError,
                    description = ResponseCodes.SystemError.DisplayName(),
                    Error = e.Message
                }));
            }
        }
        /// <summary>
        /// Checks that a SharePoint client is available to the client.
        /// </summary>
        /// <returns>The SharePoint Online client.</returns>
        public static async Task<SharePointClient> EnsureSharePointClientCreatedAsync()
        {
            try
            {
                AuthenticationContext = new AuthenticationContext(CommonAuthority);

                if (AuthenticationContext.TokenCache.ReadItems().Count() > 0)
                {
                    // Bind the AuthenticationContext to the authority that sourced the token in the cache 
                    // this is needed for the cache to work when asking for a token from that authority 
                    // (the common endpoint never triggers cache hits) 
                    string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority;
                    AuthenticationContext = new AuthenticationContext(cachedAuthority);

                }

                // Create a DiscoveryClient using the discovery endpoint Uri.  
                DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri,
                    async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId));

                // Now get the capability that you are interested in.
                CapabilityDiscoveryResult result = await discovery.DiscoverCapabilityAsync("MyFiles");

                var client = new SharePointClient(
                    result.ServiceEndpointUri,
                    async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId));

                return client;
            }
            catch (DiscoveryFailedException dfe)
            {
                MessageDialogHelper.DisplayException(dfe as Exception);

                // Discovery failed.
                AuthenticationContext.TokenCache.Clear();
                return null;
            }
            catch (MissingConfigurationValueException mcve)
            {
                MessageDialogHelper.DisplayException(mcve);

                // Connected services not added correctly, or permissions not set correctly.
                AuthenticationContext.TokenCache.Clear();
                return null;
            }
            catch (AuthenticationFailedException afe)
            {
                MessageDialogHelper.DisplayException(afe);

                // Failed to authenticate the user
                AuthenticationContext.TokenCache.Clear();
                return null;

            }
            catch (ArgumentException ae)
            {
                MessageDialogHelper.DisplayException(ae as Exception);
                // Argument exception
                AuthenticationContext.TokenCache.Clear();
                return null;
            }
        }
Example #24
0
        public EndpointDescription SelectEndpoint(string discoveryUrl, bool useSecurity)
        {
            // needs to add the '/discovery' back onto non-UA TCP URLs.
            if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp))
            {
                if (!discoveryUrl.EndsWith("/discovery"))
                {
                    discoveryUrl += "/discovery";
                }
            }

            // parse the selected URL.
            Uri uri = new Uri(discoveryUrl);

            // set a short timeout because this is happening in the drop down event.
            EndpointConfiguration configuration = EndpointConfiguration.Create();

            configuration.OperationTimeout = 5000;

            EndpointDescription selectedEndpoint = null;

            // Connect to the server's discovery endpoint and find the available configuration.
            using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration))
            {
                EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                // select the best endpoint to use based on the selected URL and the UseSecurity checkbox.
                for (int ii = 0; ii < endpoints.Count; ii++)
                {
                    EndpointDescription endpoint = endpoints[ii];

                    // check for a match on the URL scheme.
                    if (endpoint.EndpointUrl.StartsWith(uri.Scheme))
                    {
                        // check if security was requested.
                        if (useSecurity)
                        {
                            if (endpoint.SecurityMode == MessageSecurityMode.None)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (endpoint.SecurityMode != MessageSecurityMode.None)
                            {
                                continue;
                            }
                        }

                        // pick the first available endpoint by default.
                        if (selectedEndpoint == null)
                        {
                            selectedEndpoint = endpoint;
                        }

                        // The security level is a relative measure assigned by the server to the
                        // endpoints that it returns. Clients should always pick the highest level
                        // unless they have a reason not too.
                        if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel)
                        {
                            selectedEndpoint = endpoint;
                        }
                    }
                }

                // pick the first available endpoint by default.
                if (selectedEndpoint == null && endpoints.Count > 0)
                {
                    selectedEndpoint = endpoints[0];
                }
            }

            // if a server is behind a firewall it may return URLs that are not accessible to the client.
            // This problem can be avoided by assuming that the domain in the URL used to call
            // GetEndpoints can be used to access any of the endpoints. This code makes that conversion.
            // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint.

            Uri endpointUrl = Utils.ParseUri(selectedEndpoint.EndpointUrl);

            if (endpointUrl != null && endpointUrl.Scheme == uri.Scheme)
            {
                UriBuilder builder = new UriBuilder(endpointUrl);
                builder.Host = uri.DnsSafeHost;
                builder.Port = uri.Port;
                selectedEndpoint.EndpointUrl = builder.ToString();
            }

            // return the selected endpoint.
            return(selectedEndpoint);
        }
Example #25
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Welcome);

            // Create your application here
            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            //SupportActionBar.SetHomeButtonEnabled(true);
            SupportActionBar.SetHomeAsUpIndicator(null);//(Resource.Drawable.icon);
            drawerLayout = FindViewById <Android.Support.V4.Widget.DrawerLayout>(Resource.Id.drawer_layout);
            navView      = FindViewById <NavigationView>(Resource.Id.nav_view);
            navView.SetNavigationItemSelectedListener(this);

            var username = FindViewById <TextView>(Resource.Id.textViewUsername);

            username.Text = GetUsername();

            var getRequest = new Task <string>(() =>
            {
                while (true)
                {
                    var identityClient = new DiscoveryClient("http://10.27.249.82:59447"); //discover the IdentityServer
                    identityClient.Policy.RequireHttps = false;

                    var identityServer = identityClient.GetAsync().Result;

                    if (identityServer.IsError)
                    {
                        return(null);
                    }
                    //Get the token
                    var prefs    = Application.Context.GetSharedPreferences("UserInfo", FileCreationMode.Private);
                    var password = prefs.GetString("password", null);

                    var tokenClient   = new TokenClient(identityServer.TokenEndpoint, "ChatClient", "secret");
                    var tokenResponse = tokenClient.RequestResourceOwnerPasswordAsync(username.Text, password, "CallingRequestAPI").Result;


                    var client = new HttpClient();
                    client.SetBearerToken(tokenResponse.AccessToken);
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var response = client.GetAsync(string.Format("http://localhost:63653/api/CallingRequest?id={0}", 8)).Result;
                    var content  = response.Content.ReadAsStringAsync().Result;
                    if (content != "" && content != null && content != "[]")
                    {
                        var response56 = client.DeleteAsync(string.Format("http://10.27.249.82:63653/api/CallingRequest?senderID={0}&receiverID={1}", 8, 1)).Result;
                        var content56  = response56.Content.ReadAsStringAsync().Result;

                        return(content);
                    }
                }
            }
                                               );

            getRequest.Start();
        }
        private static async Task MainAsync()
        {
            // 从元数据中发现端口
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }
            // 1. 客户端授权模式-- 请求令牌
            var tokenClient   = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }
            Console.WriteLine(tokenResponse.Json);

            // 调用api
            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);
            var response = await client.GetAsync("http://localhost:5001/api/identity");

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(JArray.Parse(content));
            }

            //2. 资源所有者密码授权模式-- 请求令牌
            var tokenClientResource   = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
            var tokenResponseResource = await tokenClientResource.RequestResourceOwnerPasswordAsync("alice", "password", "api1");//使用用户名密码

            if (tokenResponseResource.IsError)
            {
                Console.WriteLine(tokenResponseResource.Error);
                return;
            }
            Console.WriteLine(tokenResponseResource.Json);

            // 调用api
            client = new HttpClient();
            client.SetBearerToken(tokenResponse.AccessToken);
            response = await client.GetAsync("http://localhost:5001/api/identity");

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(JArray.Parse(content));
            }
            //3.
        }
Example #27
0
        internal async Task EnsureProviderInformationAsync()
        {
            _logger.LogTrace("EnsureProviderInformation");

            if (useDiscovery)
            {
                if (_options.RefreshDiscoveryDocumentForLogin == false)
                {
                    // discovery document has been loaded before - skip reload
                    if (_options.ProviderInformation != null)
                    {
                        _logger.LogDebug("Skipping refresh of discovery document.");

                        return;
                    }
                }

                var client = new DiscoveryClient(_options.Authority, _options.BackchannelHandler)
                {
                    Policy  = _options.Policy.Discovery,
                    Timeout = _options.BackchannelTimeout
                };

                var disco = await client.GetAsync().ConfigureAwait(false);

                if (disco.IsError)
                {
                    _logger.LogError("Error loading discovery document: {errorType} - {error}", disco.ErrorType.ToString(), disco.Error);

                    if (disco.ErrorType == ResponseErrorType.Exception)
                    {
                        throw new InvalidOperationException("Error loading discovery document: " + disco.Error, disco.Exception);
                    }

                    throw new InvalidOperationException("Error loading discovery document: " + disco.Error);
                }

                _logger.LogDebug("Successfully loaded discovery document");
                _logger.LogDebug("Loaded keyset from {jwks_uri}", disco.JwksUri);
                _logger.LogDebug("Keyet contains the following kids: {kids}", from k in disco.KeySet.Keys select k.Kid ?? "unspecified");

                _options.ProviderInformation = new ProviderInformation
                {
                    IssuerName = disco.Issuer,
                    KeySet     = disco.KeySet,

                    AuthorizeEndpoint  = disco.AuthorizeEndpoint,
                    TokenEndpoint      = disco.TokenEndpoint,
                    EndSessionEndpoint = disco.EndSessionEndpoint,
                    UserInfoEndpoint   = disco.UserInfoEndpoint,
                    TokenEndPointAuthenticationMethods = disco.TokenEndpointAuthenticationMethodsSupported
                };
            }

            if (_options.ProviderInformation.IssuerName.IsMissing())
            {
                var error = "Issuer name is missing in provider information";

                _logger.LogError(error);
                throw new InvalidOperationException(error);
            }

            if (_options.ProviderInformation.AuthorizeEndpoint.IsMissing())
            {
                var error = "Authorize endpoint is missing in provider information";

                _logger.LogError(error);
                throw new InvalidOperationException(error);
            }

            if (_options.ProviderInformation.TokenEndpoint.IsMissing())
            {
                var error = "Token endpoint is missing in provider information";

                _logger.LogError(error);
                throw new InvalidOperationException(error);
            }

            if (_options.ProviderInformation.KeySet == null)
            {
                var error = "Key set is missing in provider information";

                _logger.LogError(error);
                throw new InvalidOperationException(error);
            }
        }
        public async Task<ActionResult> Libraries(string path)
        {
            //List<SearchResult> results = new List<SearchResult>();
            LibrariesViewModel vm = new LibrariesViewModel();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResultDisc = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResultDisc.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("RootSite");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                var authResultSharePoint = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                    new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                var sharePointToken = authResultSharePoint.AccessToken;

                ClientContext ctx = new ClientContext(path);
                ctx.ExecutingWebRequest += (sender, e) => {
                    e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + sharePointToken;
                };

                var allWebs = ctx.Web.Webs;
                var webs = ctx.LoadQuery(
                    allWebs.Include(web => web.Title, web => web.Url)
                    .Where(web => web.WebTemplate != "APP" && web.WebTemplate != "ACCSVC")
                    );
                var lists = ctx.Web.Lists;
                var docLibs = ctx.LoadQuery(
                    lists.Include(list => list.Title, list => list.Id, list => list.BaseType)
                    .Where(list => list.BaseTemplate == 101 && !list.Hidden)
                    );

                //ctx.Load(libs, splists => splists.Include(list => list.Title, list => list.Id, list => list.BaseType);
                ctx.ExecuteQuery();
                vm.SubSites = webs;
                vm.DocumentLibraries = docLibs;
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View(vm);

        }
Example #29
0
        /// <summary>
        /// Checks that an OutlookServicesClient object is available.
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task <OutlookServicesClient> GetOutlookClientAsync(string capability)
        {
            if (_outlookClient != null)
            {
                return(_outlookClient);
            }
            else
            {
                try
                {
                    //First, look for the authority used during the last authentication.
                    //If that value is not populated, use CommonAuthority.
                    string authority = null;
                    if (String.IsNullOrEmpty(LastAuthority))
                    {
                        authority = CommonAuthority;
                    }
                    else
                    {
                        authority = LastAuthority;
                    }

                    // Create an AuthenticationContext using this authority.
#if WINDOWS_APP
                    _authenticationContext = new AuthenticationContext(authority);
#endif
#if WINDOWS_PHONE_APP
                    _authenticationContext = await AuthenticationContext.CreateAsync(authority);
#endif

#if WINDOWS_APP
                    // Set the value of _authenticationContext.UseCorporateNetwork to true so that you
                    // can use this app inside a corporate intranet. If the value of UseCorporateNetwork
                    // is true, you also need to add the Enterprise Authentication, Private Networks, and
                    // Shared User Certificates capabilities in the Package.appxmanifest file.

                    _authenticationContext.UseCorporateNetwork = true;
#endif

                    //See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
                    //for an approach that improves performance by storing the discovery service information in a cache.
                    DiscoveryClient discoveryClient = new DiscoveryClient(
                        async() => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));

                    // Get the specified capability ("Mail").
                    CapabilityDiscoveryResult result =
                        await discoveryClient.DiscoverCapabilityAsync(capability);

                    var token = await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId);

                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return(null);
                    }
                    else
                    {
                        _outlookClient = new OutlookServicesClient(
                            result.ServiceEndpointUri,
                            async() => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));

                        return(_outlookClient);
                    }
                }
                // The following is a list of all exceptions you should consider handling in your app.
                // In the case of this sample, the exceptions are handled by returning null upstream.
                catch (DiscoveryFailedException dfe)
                {
                    // Discovery failed.
                    Debug.WriteLine("Exception: " + dfe.Message);
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (ArgumentException ae)
                {
                    // Argument exception
                    Debug.WriteLine("Exception: " + ae.Message);
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }
Example #30
0
        public async void FetchFullRegistryAsync_InvokesServer_ReturnsValidResponse()
        {
            var json = @"{ 
'applications': { 
    'versions__delta':'1',
    'apps__hashcode':'UP_1_',
    'application':[
        {
        'name':'FOO',
        'instance':[
            { 
            'instanceId':'localhost:foo',
            'hostName':'localhost',
            'app':'FOO',
            'ipAddr':'192.168.56.1',
            'status':'UP',
            'overriddenstatus':'UNKNOWN',
            'port':{'$':8080,'@enabled':'true'},
            'securePort':{'$':443,'@enabled':'false'},
            'countryId':1,
            'dataCenterInfo':{'@class':'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo','name':'MyOwn'},
            'leaseInfo':{'renewalIntervalInSecs':30,'durationInSecs':90,'registrationTimestamp':1457714988223,'lastRenewalTimestamp':1457716158319,'evictionTimestamp':0,'serviceUpTimestamp':1457714988223},
            'metadata':{'@class':'java.util.Collections$EmptyMap'},
            'homePageUrl':'http://localhost:8080/',
            'statusPageUrl':'http://localhost:8080/info',
            'healthCheckUrl':'http://localhost:8080/health',
            'vipAddress':'foo',
            'isCoordinatingDiscoveryServer':'false',
            'lastUpdatedTimestamp':'1457714988223',
            'lastDirtyTimestamp':'1457714988172',
            'actionType':'ADDED'
            }]
        }]
    }
}";

            IHostingEnvironment envir = new HostingEnvironment();

            TestConfigServerStartup.Response     = json;
            TestConfigServerStartup.ReturnStatus = 200;
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);
            EurekaClientConfig config = new EurekaClientConfig()
            {
                ShouldFetchRegistry      = false,
                ShouldRegisterWithEureka = false,
                EurekaServerServiceUrls  = uri.ToString()
            };

            var             httpClient = new EurekaHttpClient(config, server.CreateClient());
            DiscoveryClient client     = new DiscoveryClient(config, httpClient);
            var             result     = await client.FetchFullRegistryAsync();

            Assert.NotNull(result);
            Assert.Equal(1, result.Version);
            Assert.Equal("UP_1_", result.AppsHashCode);

            var apps = result.GetRegisteredApplications();

            Assert.NotNull(apps);
            Assert.Equal(1, apps.Count);
            Assert.Equal("FOO", apps[0].Name);
        }
Example #31
0
        public async Task<string> GetOutlookToken()
        {
            try
            {
                DiscoveryClient discoveryClient = new DiscoveryClient(
                     Office365ServicesUris.DiscoveryServiceEndpointUri,
                     async () => { return await GetAccessTokenForServiceAsync(Office365ServicesUris.DiscoveryServiceResourceId); });

                var dcr = await discoveryClient.DiscoverCapabilityAsync(Office365Capabilities.Calendar.ToString());

                return await GetAccessTokenForServiceAsync(dcr.ServiceResourceId);
            }
            catch (AdalException exception)
            {
                // Handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    this.AuthenticationContext.TokenCache.Clear();
                    throw exception;
                }
                return null;
            }
        }
Example #32
0
        public static async Task Admin3()
        {
            try
            {
                DiscoveryResponse disco = await DiscoveryClient.GetAsync("http://localhost:5000");

                if (disco.IsError)
                {
                    Console.WriteLine(disco.Error);
                    return;
                }

                TokenClient tokenClient   = new TokenClient(disco.TokenEndpoint, "superAdmin", "secret");
                var         tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

                if (tokenResponse.IsError)
                {
                    Console.WriteLine(tokenResponse.Error);
                    return;
                }
                Console.WriteLine(tokenResponse.Json);
                var client = new HttpClient();
                client.SetBearerToken(tokenResponse.AccessToken);


                Client c1 = new Client
                {
                    ClientId          = "adminClient",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets     =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "api1" },
                    Claims        = new List <Claim>
                    {
                        new Claim(JwtClaimTypes.Role, "admin")
                    },
                    ClientClaimsPrefix = "" //把client_ 前缀去掉
                };

                string      strJson = JsonConvert.SerializeObject(c1.ToEntity());
                HttpContent content = new StringContent(strJson);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");


                //由HttpClient发出Post请求
                Task <HttpResponseMessage> response = client.PostAsync("http://localhost:5000/api/values/", content);
                if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine(response.Result.StatusCode);
                }
                else
                {
                    Console.WriteLine(response.Result.Content.ReadAsStringAsync().Result);
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #33
0
        private static async Task MainAsync()
        {
            #region Resources Owner
            var discoRO = await DiscoveryClient.GetAsync("http://localhost:5050/");

            if (discoRO.IsError)
            {
                Console.WriteLine(discoRO.Error);
                return;
            }

            //Grab a bearer token using ResourceOwnerPassword Grant Type
            var tokenClientRO   = new TokenClient(discoRO.TokenEndpoint, "ro.client", "secret");
            var tokenResponseRO = await tokenClientRO.RequestResourceOwnerPasswordAsync("Manish", "password", "OAuthSampleApi");

            if (tokenResponseRO.IsError)
            {
                Console.WriteLine(tokenResponseRO.Error);
                return;
            }

            Console.WriteLine(tokenResponseRO.Json);
            Console.WriteLine("\r\n");

            #endregion

            #region ClientCredentials
            //discover all the endpoints using metadata of identity server
            var disco = await DiscoveryClient.GetAsync("http://localhost:5050/");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            //Grab a bearer token using Client Credential Grant Type
            var tokenClient   = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("OAuthSampleApi");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\r\n");

            //Consume our costumer api
            using (var client = new HttpClient())
            {
                client.SetBearerToken(tokenResponse.AccessToken);

                var customerInfo = new StringContent(JsonConvert.SerializeObject(new
                {
                    Id        = 18,
                    FirstName = "Rıdvan",
                    LastName  = "OZTURAC"
                }), Encoding.UTF8, "application/json");

                var createCustomerResponse = await client.PostAsync("http://localhost:59143/api/customers", customerInfo);

                if (!createCustomerResponse.IsSuccessStatusCode)
                {
                    Console.WriteLine(createCustomerResponse.StatusCode);
                }

                var getCustomersResponse = await client.GetAsync("http://localhost:59143/api/customers");

                if (!createCustomerResponse.IsSuccessStatusCode)
                {
                    Console.WriteLine(createCustomerResponse.StatusCode);
                }
                else
                {
                    var content = await getCustomersResponse.Content.ReadAsStringAsync();

                    Console.WriteLine(content);
                }
            }
            #endregion

            Console.ReadKey();
        }
Example #34
0
        private async Task <string> RenewTokens()
        {
            // get the current HttpContext to access the tokens
            var currentContext = _httpContextAccessor.HttpContext;

            // get the metadata
            var discoveryClient  = new DiscoveryClient(_configuration["IDPBaseAddress"]);
            var metaDataResponse = await discoveryClient.GetAsync();

            // create a new token client to get new tokens
            var tokenClient = new TokenClient(
                metaDataResponse.TokenEndpoint,
                _configuration["ClientId"],
                _configuration["ClientSecret"]);

            // get the saved refresh token
            var currentRefreshToken = await currentContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

            // refresh the tokens
            var tokenResult = await tokenClient.RequestRefreshTokenAsync(currentRefreshToken);

            if (tokenResult.IsError)
            {
                throw new Exception("Problem encountered while refreshing tokens.", tokenResult.Exception);
            }

            // update the tokens & expiration value
            var updatedTokens = new List <AuthenticationToken>();

            updatedTokens.Add(new AuthenticationToken
            {
                Name  = OpenIdConnectParameterNames.IdToken,
                Value = tokenResult.IdentityToken
            });
            updatedTokens.Add(new AuthenticationToken
            {
                Name  = OpenIdConnectParameterNames.AccessToken,
                Value = tokenResult.AccessToken
            });
            updatedTokens.Add(new AuthenticationToken
            {
                Name  = OpenIdConnectParameterNames.RefreshToken,
                Value = tokenResult.RefreshToken
            });

            var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);

            updatedTokens.Add(new AuthenticationToken
            {
                Name  = "expires_at",
                Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
            });

            // get authenticate result, containing the current principal & properties
            var currentAuthenticateResult = await currentContext.AuthenticateAsync("Cookies");

            // store the updated tokens
            currentAuthenticateResult.Properties.StoreTokens(updatedTokens);

            // sign in
            await currentContext.SignInAsync("Cookies",
                                             currentAuthenticateResult.Principal, currentAuthenticateResult.Properties);

            // return the new access token
            return(tokenResult.AccessToken);
        }
Example #35
0
 protected virtual async Task <DiscoveryResponse> GetDiscoveryResponse(IdentityClientConfiguration configuration)
 {
     return(await DiscoveryClient.GetAsync(configuration.Authority));
 }
        public async Task<ActionResult> Index()        
        {
            List<EmailMessage> myMessages = new List<EmailMessage>();

            if (User.Identity.IsAuthenticated)
            {
                var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));

                try
                {
                    DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                        async () =>
                        {
                            var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                            return authResult.AccessToken;
                        });

                    var dcr = await discClient.DiscoverCapabilityAsync("Mail");

                    OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                        async () =>
                        {
                            var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                            return authResult.AccessToken;
                        });

                    var messagesResult = await exClient.Me.Folders.GetById("Inbox").Messages.Take(20).ExecuteAsync();

                    //do
                    //{
                        var msgs = messagesResult.CurrentPage;
                        foreach (var m in msgs)
                        {
                            myMessages.Add(new EmailMessage { 
                                Subject = m.Subject,
                                Received = m.DateTimeReceived.Value.DateTime,
                                FromName = m.From.EmailAddress.Name,
                                FromEmail = m.From.EmailAddress.Address,
                                HasAttachments = m.HasAttachments.GetValueOrDefault(false),
                                Importance = m.Importance.ToString(),
                                Preview = m.BodyPreview,
                                IsRead = m.IsRead.GetValueOrDefault(false)
                            });
                        }

                        //messagesResult = await messagesResult.GetNextPageAsync();
                        //messagesResult = null;

                    //} while (messagesResult != null);
                }
                catch (AdalException exception)
                {
                    //handle token acquisition failure
                    if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                    {
                        authContext.TokenCache.Clear();

                        //handle token acquisition failure
                    }
                }
            }

            return View(myMessages);
        }
        // GET: MyFiles
        public async Task <ActionResult> Index()
        {
            List <MyFile> myFiles = new List <MyFile>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId     = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(AADAppSettings.DiscoveryServiceEndpointUri,
                                                                 async() =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(AADAppSettings.DiscoveryServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return(authResult.AccessToken);
                });

                var dcr = await discClient.DiscoverCapabilityAsync("MyFiles");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                SharePointClient spClient = new SharePointClient(dcr.ServiceEndpointUri,
                                                                 async() =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return(authResult.AccessToken);
                });

                var filesResult = await spClient.Files.ExecuteAsync();

                do
                {
                    var files = filesResult.CurrentPage.OfType <File>();

                    foreach (var file in files)
                    {
                        myFiles.Add(new MyFile {
                            Name = file.Name
                        });
                    }

                    filesResult = await filesResult.GetNextPageAsync();
                } while (filesResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return(View(myFiles));
        }
        public async Task<ActionResult> UploadFile(string path, Guid docLibId, string fileName)
        {
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            var directoryPath = Server.MapPath("~/Content/SampleFiles");
            var theFileToUpload = new System.IO.FileInfo(System.IO.Path.Combine(directoryPath, fileName));            

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                    async () =>
                    {
                        var authResultDisc = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                        return authResultDisc.AccessToken;
                    });

                var dcr = await discClient.DiscoverCapabilityAsync("RootSite");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                var authResultSharePoint = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId,
                    new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                var sharePointToken = authResultSharePoint.AccessToken;

                ClientContext ctx = new ClientContext(path);
                ctx.ExecutingWebRequest += (sender, e) =>
                {
                    e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + sharePointToken;
                };

                //Get the document library we want to upload to
                var docLib = ctx.Web.Lists.GetById(docLibId);

                ctx.Load(docLib.RootFolder);
                ctx.ExecuteQuery();

                byte[] bytes = System.IO.File.ReadAllBytes(theFileToUpload.FullName);

                ctx.RequestTimeout = 3600000;

                FileCreationInformation fci = new FileCreationInformation();
                fci.Content = bytes;
                fci.Url = $"{docLib.RootFolder.ServerRelativeUrl}/{theFileToUpload.Name}";
                fci.Overwrite = true;

                var newFile = docLib.RootFolder.Files.Add(fci);
                ctx.Load(newFile);
                ctx.ExecuteQuery();

                var absoluteUrl = new Uri(ctx.Url)
                    .GetLeftPart(UriPartial.Authority) + fci.Url;

                ViewBag.DocumentUrl = absoluteUrl;

            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return View();

        }
Example #39
0
        public async System.Threading.Tasks.Task FetchFullRegistryAsync_InvokesServer_ReturnsValidResponse()
        {
            var json = @"
                { 
                    ""applications"": { 
                        ""versions__delta"":""1"",
                        ""apps__hashcode"":""UP_1_"",
                        ""application"":[{
                            ""name"":""FOO"",
                            ""instance"":[{ 
                                ""instanceId"":""localhost:foo"",
                                ""hostName"":""localhost"",
                                ""app"":""FOO"",
                                ""ipAddr"":""192.168.56.1"",
                                ""status"":""UP"",
                                ""overriddenstatus"":""UNKNOWN"",
                                ""port"":{""$"":8080,""@enabled"":""true""},
                                ""securePort"":{""$"":443,""@enabled"":""false""},
                                ""countryId"":1,
                                ""dataCenterInfo"":{""@class"":""com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"",""name"":""MyOwn""},
                                ""leaseInfo"":{""renewalIntervalInSecs"":30,""durationInSecs"":90,""registrationTimestamp"":1457714988223,""lastRenewalTimestamp"":1457716158319,""evictionTimestamp"":0,""serviceUpTimestamp"":1457714988223},
                                ""metadata"":{""@class"":""java.util.Collections$EmptyMap""},
                                ""homePageUrl"":""http://localhost:8080/"",
                                ""statusPageUrl"":""http://localhost:8080/info"",
                                ""healthCheckUrl"":""http://localhost:8080/health"",
                                ""vipAddress"":""foo"",
                                ""isCoordinatingDiscoveryServer"":""false"",
                                ""lastUpdatedTimestamp"":""1457714988223"",
                                ""lastDirtyTimestamp"":""1457714988172"",
                                ""actionType"":""ADDED""
                            }]
                        }]
                    }
                }";

            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Response     = json;
            TestConfigServerStartup.ReturnStatus = 200;
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);
            var config = new EurekaClientConfig()
            {
                ShouldFetchRegistry      = false,
                ShouldRegisterWithEureka = false,
                EurekaServerServiceUrls  = uri.ToString()
            };

            var httpClient = new EurekaHttpClient(config, server.CreateClient());
            var client     = new DiscoveryClient(config, httpClient);
            var result     = await client.FetchFullRegistryAsync();

            Assert.NotNull(result);
            Assert.Equal(1, result.Version);
            Assert.Equal("UP_1_", result.AppsHashCode);

            var apps = result.GetRegisteredApplications();

            Assert.NotNull(apps);
            Assert.Equal(1, apps.Count);
            Assert.Equal("FOO", apps[0].Name);
        }
Example #40
0
        public static EndpointDescription CreateEndpointDescription(UAServer myServer)
        {
            // create the endpoint description.
            EndpointDescription endpointDescription = null;

            try
            {
                string discoveryUrl = myServer.ServerName;
                //OA 2018-04-27
                if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp) && !discoveryUrl.StartsWith(Utils.UriSchemeHttps))
                //if (!discoveryUrl.StartsWith(Utils.UriSchemeOpcTcp))
                {
                    if (!discoveryUrl.EndsWith("/discovery"))
                    {
                        discoveryUrl += "/discovery";
                    }
                }

                // parse the selected URL.
                Uri uri = new Uri(discoveryUrl);

                // set a short timeout because this is happening in the drop down event.
                EndpointConfiguration configuration = EndpointConfiguration.Create();
                configuration.OperationTimeout = 5000;

                //OA 2018-04-27 https
                if (discoveryUrl.StartsWith(Utils.UriSchemeHttps))
                {
                    configuration.OperationTimeout = 0;
                }
                //

                // Connect to the server's discovery endpoint and find the available configuration.
                using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration))
                {
                    EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                    // select the best endpoint to use based on the selected URL and the UseSecurity checkbox.
                    for (int ii = 0; ii < endpoints.Count; ii++)
                    {
                        EndpointDescription endpoint = endpoints[ii];

                        // check for a match on the URL scheme.
                        if (endpoint.EndpointUrl.StartsWith(uri.Scheme))
                        {
                            // check if security was requested.
                            if (!myServer.SecurityPolicy.Equals("None"))
                            {
                                if (endpoint.SecurityMode == MessageSecurityMode.None)
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (endpoint.SecurityMode != MessageSecurityMode.None)
                                {
                                    continue;
                                }
                            }

                            // pick the first available endpoint by default.
                            if (endpointDescription == null)
                            {
                                endpointDescription = endpoint;
                            }

                            // The security level is a relative measure assigned by the server to the
                            // endpoints that it returns. Clients should always pick the highest level
                            // unless they have a reason not too.
                            if (endpoint.SecurityLevel > endpointDescription.SecurityLevel)
                            {
                                endpointDescription = endpoint;
                            }
                        }
                    }

                    // pick the first available endpoint by default.
                    if (endpointDescription == null && endpoints.Count > 0)
                    {
                        endpointDescription = endpoints[0];
                    }
                }

                // if a server is behind a firewall it may return URLs that are not accessible to the client.
                // This problem can be avoided by assuming that the domain in the URL used to call
                // GetEndpoints can be used to access any of the endpoints. This code makes that conversion.
                // Note that the conversion only makes sense if discovery uses the same protocol as the endpoint.

                Uri endpointUrl = Utils.ParseUri(endpointDescription.EndpointUrl);



                if (endpointUrl != null && endpointUrl.Scheme == uri.Scheme)
                {
                    UriBuilder builder = new UriBuilder(endpointUrl);
                    builder.Host = uri.DnsSafeHost;
                    builder.Port = uri.Port;
                    endpointDescription.EndpointUrl = builder.ToString();
                }
            }
            catch
            {
                endpointDescription             = new EndpointDescription();
                endpointDescription.EndpointUrl = myServer.ServerName;

                //ABA 2014-10-10
                if (myServer.SecurityPolicy.Equals("None"))
                {
                    endpointDescription.SecurityPolicyUri = SecurityPolicies.None;
                }
                //Commented by MM 03/07/2019
                //else if (myServer.SecurityPolicy.Equals("Basic128Rsa15"))
                //{
                //    endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic128Rsa15;
                //}
                else if (myServer.SecurityPolicy.Equals("Basic256Sha256"))
                {
                    endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic256Sha256;
                }
                else if (myServer.SecurityPolicy.Equals("Basic256"))
                {
                    endpointDescription.SecurityPolicyUri = SecurityPolicies.Basic256;
                }

                try
                {
                    MessageSecurityMode myMode;
                    myMode = (MessageSecurityMode)Enum.Parse(typeof(MessageSecurityMode), myServer.SecurityMode, false);
                    //endpointDescription.SecurityMode      = MessageSecurityMode.SignAndEncrypt;
                    endpointDescription.SecurityMode = myMode;
                }
                catch
                {
                    endpointDescription.SecurityMode = MessageSecurityMode.None;
                }

                // specify the transport profile.
                if (myServer.Protocol.Equals("opc.tcp"))
                {
                    endpointDescription.TransportProfileUri = Profiles.UaTcpTransport;
                }
                //added OA 2018-04-27
                else if (myServer.Protocol.Equals("http"))
                {
                    //OA-2018-06-18  endpointDescription.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport;
                }
                else //added OA 2018-04-27
                {
                    endpointDescription.TransportProfileUri = Profiles.HttpsBinaryTransport; //OA-2018-06-18 HttpsXmlOrBinaryTransport;
                }
                //else  //OA 2018-04-27
                //{
                //    endpointDescription.TransportProfileUri = Profiles.WsHttpXmlOrBinaryTransport;
                //}

                if (myServer.UserIdentity.Equals(UserIdentityType.Certificate))
                {
                    // load the the server certificate from the local certificate store.
                    CertificateIdentifier certificateIdentifier = new CertificateIdentifier();

                    certificateIdentifier.StoreType = CertificateStoreType.X509Store; //OA-2018-06-18 .Windows;

                    if (!String.IsNullOrEmpty(myServer.CertificationStore))
                    {
                        //certificateIdentifier.StorePath = "LocalMachine\\UA Applications";
                        certificateIdentifier.StorePath = myServer.CertificationStore;
                    }
                    else
                    {
                        using (System.IO.FileStream fs = System.IO.File.OpenRead(myServer.CertificationPath))
                        {
                            byte[] bytes = new byte[fs.Length];
                            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));

                            certificateIdentifier.RawData = bytes;
                        }
                    }

                    //certificateIdentifier.SubjectName = "ONBServer";//commented by HHA 12/11//2019

                    //OA-2018-06-25
                    //X509Certificate2 serverCertificate =  certificateIdentifier.Find();
                    X509Certificate2 serverCertificate = certificateIdentifier.Find().Result;

                    if (serverCertificate == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadCertificateInvalid, "Could not find server certificate: {0}", certificateIdentifier.SubjectName);
                    }

                    endpointDescription.ServerCertificate = serverCertificate.GetRawCertData();
                }
            }

            return(endpointDescription);
        }
Example #41
0
        public async Task ExecuteAsync(CommandContext context)
        {
            context.Console.WriteLine($"Saving Server Url: {this.ServiceUrl}");
            context.Console.WriteLine($"Logging in to {this.Authority} ({this.api.Title} v{this.api.Version} running on {this.api.OS})...");

            var data = context.Repository.GetCommandData();

            if (data != null && data.Authority == this.Authority)
            {
                // already logged in?
                var discoveryResponse = default(DiscoveryResponse);
                using (var discoveryClient = new DiscoveryClient(this.Authority))
                {
                    discoveryResponse = await discoveryClient.GetAsync().ConfigureAwait(false);

                    if (!discoveryResponse.IsError)
                    {
                        using (var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "donut_console"))
                            using (var refreshTokenHandler = new RefreshTokenHandler(tokenClient, data.RefreshToken, data.AccessToken))
                                using (var userInfoClient = new UserInfoClient(discoveryResponse.UserInfoEndpoint, refreshTokenHandler))
                                {
                                    var response = await userInfoClient.GetAsync(data.AccessToken).ConfigureAwait(false);

                                    if (!response.IsError)
                                    {
                                        var claimsIdentity = new ClaimsIdentity(response.Claims, "idSvr", "name", "role");
                                        context.Console.WriteLine($"Logged in as {claimsIdentity.Name}.");
                                        return;
                                    }
                                }
                    }
                }
            }

            var browser = new SystemBrowser();
            var options = new OidcClientOptions
            {
                Authority    = this.Authority,
                ClientId     = "donut_console",
                RedirectUri  = $"http://127.0.0.1:{browser.Port}",
                Scope        = "openid profile users_api accounts_api offline_access",
                FilterClaims = false,
                Browser      = browser
            };

            var oidcClient = new OidcClient(options);
            var result     = await oidcClient.LoginAsync(new LoginRequest()).ConfigureAwait(false);

            if (result.IsError)
            {
                context.Console.Error.WriteLine($"Error attempting to log in:{Environment.NewLine}{result.Error}");
                return;
            }

            context.Repository.SetCommandData(
                new CommandData
            {
                Authority    = this.Authority,
                AccessToken  = result.AccessToken,
                RefreshToken = result.RefreshToken,
                ServiceUrl   = this.ServiceUrl,
            });

            context.Console.WriteLine($"Logged in as {result.User.Identity.Name}.");
        }
Example #42
0
        /// <summary>
        /// Use the DiscoveryClient to get the Contacts and Files endpoints
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Index(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient disco = Helpers.GetFromCache("DiscoveryClient") as DiscoveryClient;

            //Redirect to login page if we do not have an 
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {

                disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

            }

            //Discover required capabilities
            CapabilityDiscoveryResult contactsDisco = await disco.DiscoverCapabilityAsync("Contacts");
            CapabilityDiscoveryResult filesDisco = await disco.DiscoverCapabilityAsync("MyFiles");

            Helpers.SaveInCache("ContactsDiscoveryResult", contactsDisco);
            Helpers.SaveInCache("FilesDiscoveryResult", filesDisco);

            List<MyDiscovery> discoveries = new List<MyDiscovery>(){
                new MyDiscovery(){
                    Capability = "Contacts",
                    EndpointUri = contactsDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = contactsDisco.ServiceResourceId,
                    Version = contactsDisco.ServiceApiVersion
                },
                new MyDiscovery(){
                    Capability = "My Files",
                    EndpointUri = filesDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = filesDisco.ServiceResourceId,
                    Version = filesDisco.ServiceApiVersion
                }
            };

            return View(discoveries);

        }
        private void DiscoveryClient_FindCompleted(object sender, FindCompletedEventArgs e)
        {
            tracer.TraceEvent(TraceEventType.Verbose, 0, "ScreenCastControl::FindCompleted(...)");

            // logger.Debug("FindCompleted(...)");

            finding = false;

            List <ComboBoxItem> hostItems = new List <ComboBoxItem>();

            if (e.Cancelled)
            {
                //logger.Debug("Cancelled");
                tracer.Verb("ScreenCastControl::FindCompleted(...) Cancelled");
            }
            if (e.Error != null)
            {
                // logger.Debug(e.Error.ToString());
                tracer.Error(e.Error);
            }


            if (!e.Cancelled)
            {
                var result = e.Result;
                if (result != null)
                {
                    foreach (var ep in result.Endpoints)
                    {
                        string address  = ep.Address.ToString();
                        string hostName = address;

                        var extensions = ep.Extensions;
                        if (extensions != null && extensions.Count > 0)
                        {
                            var hostElement = extensions.FirstOrDefault(el => el.Name == "HostName");
                            if (hostElement != null)
                            {
                                hostName = hostElement.Value;// + " {" + address + "}";
                            }
                        }

                        //logger.Debug(hostName);

                        hostItems.Add(new ComboBoxItem
                        {
                            Name = hostName,
                            Tag  = address,
                        });
                    }
                }
            }

            hostsComboBox.DataSource    = hostItems;
            hostsComboBox.DisplayMember = "Name";

            discoveryClient.Close();
            discoveryClient = null;

            connectButton.Enabled = true;
            hostsComboBox.Enabled = true;

            findServiceButton.Text = "_Find";
            labelStatus.Text       = "_Not Connected";
        }
        /// <summary>
        /// Finds the endpoint that best matches the current settings.
        /// </summary>
        /// <param name="discoveryUrl">The discovery URL.</param>
        /// <param name="useSecurity">if set to <c>true</c> select an endpoint that uses security.</param>
        /// <param name="operationTimeout">Optional. Operation timeout in milliseconds.</param>
        /// <returns>The best available endpoint.</returns>
        public static EndpointDescription SelectEndpoint(string discoveryUrl, bool useSecurity, int operationTimeout = -1)
        {
            // needs to add the '/discovery' back onto non-UA TCP URLs.
            if (discoveryUrl.StartsWith(Utils.UriSchemeHttps))
            {
                if (!discoveryUrl.EndsWith("/discovery"))
                {
                    discoveryUrl += "/discovery";
                }
            }

            // parse the selected URL.
            Uri uri = new Uri(discoveryUrl);

            EndpointConfiguration configuration = EndpointConfiguration.Create();

            if (operationTimeout > 0)
            {
                configuration.OperationTimeout = operationTimeout;
            }

            EndpointDescription selectedEndpoint = null;

            // Connect to the server's discovery endpoint and find the available configuration.
            using (DiscoveryClient client = DiscoveryClient.Create(uri, configuration))
            {
                EndpointDescriptionCollection endpoints = client.GetEndpoints(null);

                // select the best endpoint to use based on the selected URL and the UseSecurity checkbox.
                for (int ii = 0; ii < endpoints.Count; ii++)
                {
                    EndpointDescription endpoint = endpoints[ii];

                    // check for a match on the URL scheme.
                    if (endpoint.EndpointUrl.StartsWith(uri.Scheme))
                    {
                        // check if security was requested.
                        if (useSecurity)
                        {
                            if (endpoint.SecurityMode == MessageSecurityMode.None)
                            {
                                continue;
                            }

                            // skip unsupported security policies
                            if (SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri) == null)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (endpoint.SecurityMode != MessageSecurityMode.None)
                            {
                                continue;
                            }
                        }

                        // pick the first available endpoint by default.
                        if (selectedEndpoint == null)
                        {
                            selectedEndpoint = endpoint;
                        }

                        // The security level is a relative measure assigned by the server to the
                        // endpoints that it returns. Clients should always pick the highest level
                        // unless they have a reason not too.
                        if (endpoint.SecurityLevel > selectedEndpoint.SecurityLevel)
                        {
                            selectedEndpoint = endpoint;
                        }
                    }
                }

                // pick the first available endpoint by default.
                if (selectedEndpoint == null && endpoints.Count > 0)
                {
                    selectedEndpoint = endpoints[0];
                }
            }

            // return the selected endpoint.
            return(selectedEndpoint);
        }
        ////services
        //private readonly IUserRepository _userRepository;

        //public ProfileService(IUserRepository userRepository)
        //{
        //    _userRepository = userRepository;
        //}

        //Get user profile date in terms of claims when calling /connect/userinfo
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            try
            {
                //depending on the scope accessing the user data.
                if (!string.IsNullOrEmpty(context.Subject.Identity.Name))
                {
                    DiscoveryResponse disco = await DiscoveryClient.GetAsync("http://localhost:5000");

                    TokenClient tokenClient   = new TokenClient(disco.TokenEndpoint, "MvcServer", "secret");
                    var         tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

                    var client = new HttpClient();
                    client.SetBearerToken(tokenResponse.AccessToken);
                    var response = await client.GetAsync("http://localhost:5001/api/values/" + context.Subject.Identity.Name);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception("Resource server is not working!");
                    }
                    else
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        User user = JsonConvert.DeserializeObject <User>(content);
                        //get user from db (in my case this is by email)
                        //var user = await _userRepository.FindAsync(context.Subject.Identity.Name);
                        if (user != null)
                        {
                            var claims = GetUserClaims(user);

                            //set issued claims to return
                            //context.IssuedClaims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
                            context.IssuedClaims = claims.ToList();
                        }
                    }
                }
                else
                {
                    //get subject from context (this was set ResourceOwnerPasswordValidator.ValidateAsync),
                    //where and subject was set to my user id.
                    var userId = context.Subject.Claims.FirstOrDefault(x => x.Type == "sub");

                    if (!string.IsNullOrEmpty(userId?.Value) && long.Parse(userId.Value) > 0)
                    {
                        DiscoveryResponse disco = await DiscoveryClient.GetAsync("http://localhost:5000");

                        TokenClient tokenClient   = new TokenClient(disco.TokenEndpoint, "MvcServer", "secret");
                        var         tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

                        var client = new HttpClient();
                        client.SetBearerToken(tokenResponse.AccessToken);
                        var response = await client.GetAsync("http://localhost:5001/api/values/" + long.Parse(userId.Value));

                        //get user from db (find user by user id)
                        //var user = await _userRepository.FindAsync(long.Parse(userId.Value));
                        var content = await response.Content.ReadAsStringAsync();

                        User user = JsonConvert.DeserializeObject <User>(content);
                        // issue the claims for the user
                        if (user != null)
                        {
                            var claims = ResourceOwnerPasswordValidator.GetUserClaims(user);

                            context.IssuedClaims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //log your error
            }
        }
        private static async Task MainAsync()
        {
            try
            {
                Console.WriteLine("Calling IdentityServer4 discovery endpoint...");
                Console.WriteLine(Environment.NewLine);

                var discoveryUrl      = "https://*****:*****@ssw0rd";
                var discoveryClient   = new DiscoveryClient(discoveryUrl);
                var discoveryResponse = await discoveryClient.GetAsync();

                if (discoveryResponse.IsError)
                {
                    throw new Exception("Failed to get discovery response!");
                }

                Console.WriteLine("Calling IdentityServer4 authorize endpoint to get request token...");
                Console.WriteLine(Environment.NewLine);

                var scope         = "widgetapi";
                var tokenClient   = new TokenClient(discoveryResponse.TokenEndpoint, clientId, clientSecret);
                var tokenResponse = await tokenClient.RequestClientCredentialsAsync(scope);

                if (tokenResponse.IsError)
                {
                    throw new Exception("Authentication failed!");
                }

                Console.WriteLine("Calling Ocelot endpoint with bearer token to get widgets...");
                Console.WriteLine(Environment.NewLine);

                var uri           = "https://localhost:44371/api/v1/widget";
                var gatewayClient = new HttpClient();
                gatewayClient.SetBearerToken(tokenResponse.AccessToken);
                var response = await gatewayClient.GetAsync(uri);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Received HTTP 200 from API. Writing widgets to console...");
                    Console.WriteLine(Environment.NewLine);

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

                    Console.WriteLine(content);
                }
                else
                {
                    Console.WriteLine("Response was unsuccessful with status code: " + response.StatusCode);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(Environment.NewLine);
            }

            Console.WriteLine("Press ENTER to quit.");
            Console.ReadLine();
        }
 public AdminController(IConfigStore configStore, EntityClient entityClient, ILogger <AdminController> logger, DiscoveryClient discoveryClient)
 {
     ConfigStore     = configStore;
     EntityClient    = entityClient;
     Logger          = logger;
     DiscoveryClient = discoveryClient;
 }
        private async Task <bool> InitializeIdentityServer()
        {
            _identityServerResponse = await DiscoveryClient.GetAsync(ConstantsHelper.IdentityServerUrl);

            return(!_identityServerResponse.IsError);
        }
Example #49
0
        private static async Task MainAsync()
        {
            var discoRO = await DiscoveryClient.GetAsync("http://localhost:5000");

            if (discoRO.IsError)
            {
                Console.WriteLine(discoRO.Error);
                return;
            }

            // Grab a bearer token using ResourceOwnerPassword Grant Type
            var tokenClientRO   = new TokenClient(discoRO.TokenEndpoint, "ro.client", "secret");
            var tokenResponseRO = await tokenClientRO.RequestResourceOwnerPasswordAsync("Renan", "password", "BankOfDotNetApi");

            if (tokenResponseRO.IsError)
            {
                Console.WriteLine(tokenResponseRO.Error);
                return;
            }

            Console.WriteLine(tokenResponseRO.Json);
            Console.WriteLine("\n\n");



            //discover all the endpoints using metada of identity server
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // Grab a bearer token using Client Credential Grant Type
            var tokenClient   = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("BankOfDotNetApi");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            //Consume our customer API
            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);

            var customerInfo = new StringContent(
                JsonConvert.SerializeObject(
                    new { Id = 1, FirstName = "Renan", LastName = "Santos" }
                    ), Encoding.UTF8, "application/json");

            var createCustomerResponse = await client.PostAsync("http://localhost:60169/api/Customers", customerInfo);

            if (!createCustomerResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(createCustomerResponse.StatusCode);
            }

            var getCustomerResponse = await client.GetAsync("http://localhost:60169/api/Customers");

            if (!getCustomerResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(getCustomerResponse.StatusCode);
            }
            else
            {
                var content = await getCustomerResponse.Content.ReadAsStringAsync();

                Console.WriteLine(JArray.Parse(content));
            }
            Console.Read();
        }
Example #50
0
        internal void ConfigureJwtBearer(JwtBearerOptions jwtOptions)
        {
            jwtOptions.Authority                  = Authority;
            jwtOptions.RequireHttpsMetadata       = RequireHttpsMetadata;
            jwtOptions.BackchannelTimeout         = BackChannelTimeouts;
            jwtOptions.RefreshOnIssuerKeyNotFound = true;
            jwtOptions.SaveToken                  = SaveToken;

            jwtOptions.Events = new JwtBearerEvents
            {
                OnMessageReceived = e =>
                {
                    e.Token = InternalTokenRetriever(e.Request);
                    return(JwtBearerEvents.MessageReceived(e));
                },

                OnTokenValidated       = e => JwtBearerEvents.TokenValidated(e),
                OnAuthenticationFailed = e => JwtBearerEvents.AuthenticationFailed(e),
                OnChallenge            = e => JwtBearerEvents.Challenge(e)
            };

            if (DiscoveryDocumentRefreshInterval.HasValue)
            {
                var parsedUrl = DiscoveryClient.ParseUrl(Authority);

                var httpClient = new HttpClient(JwtBackChannelHandler ?? new HttpClientHandler())
                {
                    Timeout = BackChannelTimeouts,
                    MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10 MB
                };

                var manager = new ConfigurationManager <OpenIdConnectConfiguration>(
                    parsedUrl.Url,
                    new OpenIdConnectConfigurationRetriever(),
                    new HttpDocumentRetriever(httpClient)
                {
                    RequireHttps = RequireHttpsMetadata
                })
                {
                    AutomaticRefreshInterval = DiscoveryDocumentRefreshInterval.Value
                };

                jwtOptions.ConfigurationManager = manager;
            }

            if (JwtBackChannelHandler != null)
            {
                jwtOptions.BackchannelHttpHandler = JwtBackChannelHandler;
            }

            // if API name is set, do a strict audience check for
            if (!string.IsNullOrWhiteSpace(ApiName) && !LegacyAudienceValidation)
            {
                jwtOptions.Audience = ApiName;
            }
            else
            {
                // no audience validation, rely on scope checks only
                jwtOptions.TokenValidationParameters.ValidateAudience = false;
            }

            jwtOptions.TokenValidationParameters.NameClaimType = NameClaimType;
            jwtOptions.TokenValidationParameters.RoleClaimType = RoleClaimType;

            //jwtOptions.TokenValidationParameters.ClockSkew=TimeSpan.FromSeconds(10);
            if (JwtValidationClockSkew.HasValue)
            {
                jwtOptions.TokenValidationParameters.ClockSkew = JwtValidationClockSkew.Value;
            }

            if (InboundJwtClaimTypeMap != null)
            {
                var handler = new JwtSecurityTokenHandler
                {
                    InboundClaimTypeMap = InboundJwtClaimTypeMap
                };

                jwtOptions.SecurityTokenValidators.Clear();
                jwtOptions.SecurityTokenValidators.Add(handler);
            }
        }
Example #51
0
        public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request,
                                                                                        ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation)
        {
            var attribute = (CheckPolicyAttribute)continuation.Method.GetCustomAttributes(typeof(CheckPolicyAttribute), false).FirstOrDefault();

            if (attribute == null)
            {
                return(await continuation(request, context));
            }

            var userToken = string.Empty;

            if (context.RequestHeaders.Any(x => x.Key == "Authorization"))
            {
                userToken = context.RequestHeaders.FirstOrDefault(x => x.Key == "Authorization")?.Value;
            }
            else
            {
                if (_hostingEnvironment.IsDevelopment())
                {
                    userToken = _config.GetValue <string>("Jwt_Token_Dev");
                }
            }

            var disco = await DiscoveryClient.GetAsync(_config.GetValue <string>("AuthorityUri"));

            var keys = new List <SecurityKey>();

            foreach (var webKey in disco.KeySet.Keys)
            {
                var e = Base64Url.Decode(webKey.E);
                var n = Base64Url.Decode(webKey.N);

                var key = new RsaSecurityKey(new RSAParameters {
                    Exponent = e, Modulus = n
                })
                {
                    KeyId = webKey.Kid
                };

                keys.Add(key);
            }

            var parameters = new TokenValidationParameters
            {
                ValidIssuer       = disco.Issuer,
                ValidAudience     = _config.GetValue <string>("Jwt_Audience"),
                IssuerSigningKeys = keys,

                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role,

                RequireSignedTokens = true,
                ValidateLifetime    = false
            };

            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();

            var user = handler.ValidateToken(userToken.TrimStart("Bearer").TrimStart(" "), parameters, out _);

            if (!user.HasClaim(c => c.Value == attribute.Name))
            {
                throw new AuthenticationException("Couldn't access to this API, please check your permission.");
            }

            return(await continuation(request, context));
        }
        public void FindAvailableServices()
        {
            try
            {
                IsSearchingForEndPoints = true;

                AvailableEndpointsChanged?.Invoke(this, new EventArgs());

                var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
                var findResponse    = discoveryClient.Find(new FindCriteria(typeof(IDataServiceServer))
                {
                    Duration = TimeSpan.FromSeconds(2)
                });

                foreach (var endPoints in findResponse.Endpoints)
                {
                    var found = false;

                    foreach (var knownEndpoint in _availableEndpoints)
                    {
                        if (knownEndpoint.Uri == endPoints.Address.Uri)
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        lock (_availableEndpoints)
                        {
                            _availableEndpoints.Add(endPoints.Address);
                            AvailableEndpointsChanged?.Invoke(this, new EventArgs());
                        }
                    }
                }

                foreach (var knownEndpoint in _availableEndpoints.ToList())
                {
                    var found = false;
                    foreach (var endPoints in findResponse.Endpoints)
                    {
                        if (knownEndpoint.Uri == endPoints.Address.Uri)
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        lock (_availableEndpoints)
                        {
                            _availableEndpoints.Remove(knownEndpoint);
                            AvailableEndpointsChanged?.Invoke(this, new EventArgs());
                        }
                    }
                }
            }
            finally
            {
                IsSearchingForEndPoints = false;

                AvailableEndpointsChanged?.Invoke(this, new EventArgs());
            }
        }
        /// <summary>
        /// Perform a single discovery using a discovery url
        /// </summary>
        /// <param name="discoveryUrl"></param>
        /// <param name="localeIds"></param>
        /// <param name="caps"></param>
        /// <param name="timeout"></param>
        /// <param name="visitedUris"></param>
        /// <param name="queue"></param>
        /// <param name="result"></param>
        private async Task DiscoverAsync(Uri discoveryUrl, StringCollection localeIds,
                                         IEnumerable <string> caps, int timeout, HashSet <string> visitedUris,
                                         Queue <Tuple <Uri, List <string> > > queue, HashSet <DiscoveredEndpointModel> result)
        {
            var configuration = EndpointConfiguration.Create(_appConfig);

            configuration.OperationTimeout = timeout;
            using (var client = DiscoveryClient.Create(discoveryUrl, configuration)) {
                //
                // Get endpoints from current discovery server
                //
                var endpoints = await client.GetEndpointsAsync(null,
                                                               client.Endpoint.EndpointUrl, localeIds, null);

                if (!(endpoints?.Endpoints?.Any() ?? false))
                {
                    _logger.Debug("No endpoints at {discoveryUrl}...", discoveryUrl);
                    return;
                }
                _logger.Debug("Found endpoints at {discoveryUrl}...", discoveryUrl);

                foreach (var ep in endpoints.Endpoints.Where(ep =>
                                                             ep.Server.ApplicationType != Opc.Ua.ApplicationType.DiscoveryServer))
                {
                    result.Add(new DiscoveredEndpointModel {
                        Description           = ep, // Reported
                        AccessibleEndpointUrl = new UriBuilder(ep.EndpointUrl)
                        {
                            Host = discoveryUrl.DnsSafeHost
                        }.ToString(),
                        Capabilities = new HashSet <string>(caps)
                    });
                }

                //
                // Now Find servers on network.  This might fail for old lds
                // as well as reference servers, then we call FindServers...
                //
                try {
                    var response = await client.FindServersOnNetworkAsync(null, 0, 1000,
                                                                          new StringCollection());

                    var servers = response?.Servers ?? new ServerOnNetworkCollection();
                    foreach (var server in servers)
                    {
                        var url = CreateDiscoveryUri(server.DiscoveryUrl, discoveryUrl.Port);
                        if (!visitedUris.Contains(url))
                        {
                            queue.Enqueue(Tuple.Create(discoveryUrl,
                                                       server.ServerCapabilities.ToList()));
                            visitedUris.Add(url);
                        }
                    }
                }
                catch {
                    // Old lds, just continue...
                    _logger.Debug("{discoveryUrl} does not support ME extension...",
                                  discoveryUrl);
                }

                //
                // Call FindServers first to push more unique discovery urls
                // into the discovery queue
                //
                var found = await client.FindServersAsync(null,
                                                          client.Endpoint.EndpointUrl, localeIds, null);

                if (found?.Servers != null)
                {
                    var servers = found.Servers.SelectMany(s => s.DiscoveryUrls);
                    foreach (var server in servers)
                    {
                        var url = CreateDiscoveryUri(server, discoveryUrl.Port);
                        if (!visitedUris.Contains(url))
                        {
                            queue.Enqueue(Tuple.Create(discoveryUrl, new List <string>()));
                            visitedUris.Add(url);
                        }
                    }
                }
            }
        }
        public static async Task <DiscoveryResponse> GetDiscoveryDocument(string authority)
        {
            var discoClient = new DiscoveryClient(authority);

            return(await discoClient.GetAsync());
        }
        private void GetService(string capability, out Uri serviceEndpointUri, out string serviceResourceId)
        {
            var discoveryClient = new DiscoveryClient(DiscoveryServiceEndpointUri,
                async () => await AuthenticationHelperSDK.GetTokenAsync(DiscoveryResourceId));

            CapabilityDiscoveryResult result = discoveryClient.DiscoverCapabilityAsync(capability).Result;
            serviceEndpointUri = result.ServiceEndpointUri;
            serviceResourceId = result.ServiceResourceId;
        }
Example #56
0
        private static async Task MainAsync()
        {
            //Discover Endpoints using Metadata of IdentityServer

            var Discovery = await DiscoveryClient.GetAsync("http://localhost:5000");

            if (Discovery.IsError)
            {
                Console.WriteLine(Discovery.Error);
            }



            //Grab a Bearer Token Using Client Credentials FLow Grant Type

            var tokenClient   = new TokenClient(Discovery.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("bankApi");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
            }
            Console.WriteLine("\nGrant Type Flow\n\n");
            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");


            //Grab a Bearer Token Using Resource Owner FLow Grant Type

            var tokenClientRO   = new TokenClient(Discovery.TokenEndpoint, "ro.client", "secret");
            var tokenResponseRO = await tokenClientRO.RequestResourceOwnerPasswordAsync("Kajol", "password", "bankApi");

            if (tokenResponseRO.IsError)
            {
                Console.WriteLine(tokenResponseRO.Error);
            }
            Console.WriteLine("\nResource Owner Flow\n\n");
            Console.WriteLine(tokenResponseRO.Json);
            Console.WriteLine("\n\n");

            //Consume our CLient APi
            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);
            var customerInfo = new StringContent(
                JsonConvert.SerializeObject(new { Id = 1, FirstName = "Lokesh", LastName = "Kashyap" }),
                Encoding.UTF8, "application/json");
            var createCustomerResponse = await client.PostAsync("https://localhost:44304/api/customers", customerInfo);

            if (!createCustomerResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(createCustomerResponse.StatusCode);
            }

            var getCustomerResponse = await client.GetAsync("https://localhost:44304/api/customers");

            if (!getCustomerResponse.IsSuccessStatusCode)
            {
                Console.WriteLine(getCustomerResponse.StatusCode);
            }
            else
            {
                var content = await getCustomerResponse.Content.ReadAsStringAsync();

                Console.WriteLine(JArray.Parse(content));
            }

            Console.ReadKey();
        }
        /// <summary>
        /// Checks that an OutlookServicesClient object is available. 
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task<OutlookServicesClient> GetOutlookClientAsync(string capability)
        {
            if (_outlookClient != null)
            {
                return _outlookClient;
            }
            else
            {
                try
                {
                    //First, look for the authority used during the last authentication.
                    //If that value is not populated, use CommonAuthority.
                    string authority = null;
                    if (String.IsNullOrEmpty(LastAuthority))
                    {
                        authority = CommonAuthority;
                    }
                    else
                    {
                        authority = LastAuthority;
                    }

                    // Create an AuthenticationContext using this authority.
                    _authenticationContext = new AuthenticationContext(authority);

                    // Set the value of _authenticationContext.UseCorporateNetwork to true so that you 
                    // can use this app inside a corporate intranet. If the value of UseCorporateNetwork 
                    // is true, you also need to add the Enterprise Authentication, Private Networks, and
                    // Shared User Certificates capabilities in the Package.appxmanifest file.
                    _authenticationContext.UseCorporateNetwork = true;

                    //See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
                    //for an approach that improves performance by storing the discovery service information in a cache.
                    DiscoveryClient discoveryClient = new DiscoveryClient(
                        async () => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));

                    // Get the specified capability ("Mail").
                    CapabilityDiscoveryResult result =
                        await discoveryClient.DiscoverCapabilityAsync(capability);

                    var token = await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId);
                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return null;
                    }
                    else
                    {

                        _outlookClient = new OutlookServicesClient(
                            result.ServiceEndpointUri,
                            async () => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));

                        return _outlookClient;
                    }
                }
                // The following is a list of all exceptions you should consider handling in your app.
                // In the case of this sample, the exceptions are handled by returning null upstream. 
                catch (DiscoveryFailedException dfe)
                {

                    // Discovery failed.
                    Debug.WriteLine("Exception: " + dfe.Message);
                    _authenticationContext.TokenCache.Clear();
                    return null;
                }
                catch (ArgumentException ae)
                {
                    // Argument exception
                    Debug.WriteLine("Exception: " + ae.Message);
                    _authenticationContext.TokenCache.Clear();
                    return null;
                }
            }
       }
Example #58
0
        private static async Task MainAsync()
        {
            //需要修改的配置
            var configuration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>
                {
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/api/values",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 10001,
                            },
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 10002,
                            }
                        },
                        DownstreamScheme     = "http",
                        UpstreamPathTemplate = "/c/api/values",
                        UpstreamHttpMethod   = new List <string> {
                            "Get", "Post"
                        }
                    }
                },
                GlobalConfiguration = new FileGlobalConfiguration
                {
                    BaseUrl = "http://localhost:10000/"
                }
            };

            // 从元数据中发现客户端
            var disco = await DiscoveryClient.GetAsync("http://localhost:9500");

            // 请求令牌
            var tokenClient   = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("s2api");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);

            HttpContent content = new StringContent(JsonConvert.SerializeObject(configuration));

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync("http://localhost:10000/admin/configuration", content);

            Console.WriteLine("update ocelot config sucess");
            Console.ReadLine();
        }
        public async Task<ActionResult> Contacts()
        {
            List<Persona> myContacts = new List<Persona>();

            if (User.Identity.IsAuthenticated)
            {
                var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));

                try
                {
                    DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                        async () =>
                        {
                            var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                            return authResult.AccessToken;
                        });

                    var dcr = await discClient.DiscoverCapabilityAsync("Contacts");

                    OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                        async () =>
                        {
                            var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                            return authResult.AccessToken;
                        });

                    var contactsResult = await exClient.Me.Contacts.Take(20).ExecuteAsync();

                    //do
                    //{
                        var contacts = contactsResult.CurrentPage;
                        foreach (var c in contacts)
                        {
                            var firstEmail = c.EmailAddresses.FirstOrDefault();
                            string email = "";
                            if (firstEmail != null) email = firstEmail.Address;

                            myContacts.Add(new Persona
                            {
                                DisplayName = c.DisplayName,
                                Email = email,
                                JobTitle = c.JobTitle,
                                CompanyName = c.CompanyName,
                                Im = c.ImAddresses.FirstOrDefault(),
                                OfficeLocation = c.OfficeLocation,
                                Phone = c.BusinessPhones.FirstOrDefault()
                            });
                        }

                    //    contactsResult = await contactsResult.GetNextPageAsync();

                    //} while (contactsResult != null);
                }
                catch (AdalException exception)
                {
                    //handle token acquisition failure
                    if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                    {
                        authContext.TokenCache.Clear();

                        //handle token acquisition failure
                    }
                }
            }

            return View(myContacts);
        }
Example #60
0
        static async Task RunAsync()
        {
            /*
             * Client credentials and customerId
             *
             * Here Oauth2 is being used with "client credentials": The "client" is the application, and we require a secret
             * known only to the application.
             *
             */

            var clientId   = "******************************";
            var secret     = "******************************";
            var customerId = "*****************";

            /** Setup constants */
            var discoveryEndpoint = "https://auth.sbanken.no/identityserver";
            var apiBaseAddress    = "https://api.sbanken.no";
            var bankBasePath      = "/exec.bank";
            var customersBasePath = "/exec.customers";

            /**
             * Connect to Sbanken
             *
             * Here the application connect to the identity server endpoint to retrieve a access token.
             */

            // First: get the OpenId configuration from Sbanken.
            var discoClient = new DiscoveryClient(discoveryEndpoint);

            var x = discoClient.Policy = new DiscoveryPolicy()
            {
                ValidateIssuerName = false,
            };

            var discoResult = await discoClient.GetAsync();

            if (discoResult.Error != null)
            {
                throw new Exception(discoResult.Error);
            }

            // The application now knows how to talk to the token endpoint.

            // Second: the application authenticates against the token endpoint
            var tokenClient = new TokenClient(discoResult.TokenEndpoint, clientId, secret);

            var tokenResponse = tokenClient.RequestClientCredentialsAsync().Result;

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.ErrorDescription);
            }

            // The application now has an access token.

            var httpClient = new HttpClient()
            {
                BaseAddress           = new Uri(apiBaseAddress),
                DefaultRequestHeaders =
                {
                    { "customerId", customerId }
                }
            };

            // Finally: Set the access token on the connecting client.
            // It will be used with all requests against the API endpoints.
            httpClient.SetBearerToken(tokenResponse.AccessToken);

            // The application retrieves the customer's information.
            var customerResponse = await httpClient.GetAsync($"{customersBasePath}/api/v1/Customers");

            var customerResult = await customerResponse.Content.ReadAsStringAsync();

            Trace.WriteLine($"CustomerResult:{customerResult}");

            // The application retrieves the customer's accounts.
            var accountResponse = await httpClient.GetAsync($"{bankBasePath}/api/v1/Accounts");

            var accountResult = await accountResponse.Content.ReadAsStringAsync();

            var accountsList = JsonConvert.DeserializeObject <AccountsList>(accountResult);

            Trace.WriteLine($"AccountResult:{accountResult}");

            var spesificAccountResponse = await httpClient.GetAsync($"{bankBasePath}/api/v1/Accounts/{accountsList.Items[0].AccountId}");

            var spesificAccountResult = await spesificAccountResponse.Content.ReadAsStringAsync();


            Trace.WriteLine($"SpesificAccountResult:{spesificAccountResult}");
        }