コード例 #1
0
        /// <summary>
        /// Discover the authority for authentication.
        /// </summary>
        /// <param name="serviceUrl">The SOAP endpoint for a tenant organization.</param>
        /// <returns>The decoded authority URL.</returns>
        /// <remarks>The passed service URL string must contain the SdkClientVersion property.
        /// Otherwise, the discovery feature will not be available.</remarks>
        public async Task <string> DiscoveryAuthority()
        {
            AuthenticationParameters ap = await
                                          AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(props.OrgUri + "/api/data/"));

            return(ap.Authority);
        }
コード例 #2
0
        public IEnumerable <string> Get()
        {
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                new Uri("https://ecasbc.crm3.dynamics.com/api/data/")).Result;

            String authorityUrl = ap.Authority;
            String resourceUrl  = ap.Resource;

            JObject contact1 = new JObject();

            contact1.Add("firstname", "Peter");
            contact1.Add("lastname", "Cambel");
            contact1.Add("annualincome", 80000);
            contact1["jobtitle"] = "Junior Developer";

            var httpClient = new Authentication().getOnPremHttpClient("vdantas", "", "IDIR", "https://dangle.dev.jag.gov.bc.ca/LCRB-CLLCMS-DEV/api/data/v8.2/");
            //var httpClient = new Authentication().getOnlineHttpClient(resourceUrl, authorityUrl, "ec8867d2-fa01-4fa3-8d45-f23aeddf3449", "http://localhost", "*****@*****.**");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "contacts");

            request.Content = new StringContent(contact1.ToString(), Encoding.UTF8, "application/json");
            HttpResponseMessage response = httpClient.SendAsync(request).Result;

            return(new string[] { "value1", "value2" });
        }
コード例 #3
0
        /// <summary>
        /// Discover the authentication authority.
        /// </summary>
        /// <returns>The URL of the authentication authority on the specified endpoint address, or an empty string
        /// if the authority cannot be discovered.</returns>
        public static string DiscoverAuthority(string serviceUrl)
        {
            try
            {
                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(serviceUrl + "api/data/")).Result;

                return(ap.Authority);
            }
            catch (HttpRequestException e)
            {
                throw new Exception("An HTTP request exception occurred during authority discovery.", e);
            }
            catch (System.Exception e)
            {
                // This exception ocurrs when the service is not configured for OAuth.
                if (e.HResult == -2146233088)
                {
                    return(String.Empty);
                }
                else
                {
                    throw e;
                }
            }
        }
コード例 #4
0
        public string GetToken()
        {
            if (!string.IsNullOrWhiteSpace(this._token) && this._tokenExpiry > DateTimeOffset.Now.AddMinutes(5))
            {
                return(this._token);
            }

            //lock (this._lockObject)
            {
                if (!string.IsNullOrWhiteSpace(this._token) && this._tokenExpiry > DateTimeOffset.Now.AddMinutes(5))
                {
                    return(this._token);
                }

                if (string.IsNullOrWhiteSpace(this._token) || (!string.IsNullOrWhiteSpace(this._token) && this._tokenExpiry < DateTimeOffset.Now.AddMinutes(5)))
                {
                    AuthenticationParameters app = AuthenticationParameters.CreateFromResourceUrlAsync(
                        new Uri(_resource)).Result;
                    var authContext = new AuthenticationContext(app.Authority, false);          // (this._authority, false);
                    var cred        = new ClientCredential(_clientId, _clientSecret);           //new UserCredential(_username, this._password);
                    var result      = authContext.AcquireTokenAsync(app.Resource, cred).Result; // authContext.AcquireTokenAsync(_resource, cred).Result;//.AcquireToken(this._resource, this._clientId, cred);

                    this._tokenExpiry = result.ExpiresOn;
                    this._token       = result.AccessToken;             // "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImlCakwxUmNxemhpeTRmcHhJeGRacW9oTTJZayIsImtpZCI6ImlCakwxUmNxemhpeTRmcHhJeGRacW9oTTJZayJ9.eyJhdWQiOiJodHRwczovL2RlZnJhLWN1c3RtYXN0LWRldi5jcm00LmR5bmFtaWNzLmNvbS8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82ZjUwNDExMy02YjY0LTQzZjItYWRlOS0yNDJlMDU3ODAwMDcvIiwiaWF0IjoxNTI3NzcxOTM4LCJuYmYiOjE1Mjc3NzE5MzgsImV4cCI6MTUyNzc3NTgzOCwiYWNyIjoiMSIsImFpbyI6IlkyZGdZTGovaERQVFNqWWl1dWQ0VWZ2bFA4ZlpaalN0L0xGb1o1Z1NxL0oxaTd2NmYvVUIiLCJhbXIiOlsicHdkIl0sImFwcGlkIjoiMTgwMWQ4M2ItNTRmZi00ZjYzLWJjZmUtOTEzM2E0ZTE2OGZjIiwiYXBwaWRhY3IiOiIwIiwiZV9leHAiOjI2MjgwMCwiZmFtaWx5X25hbWUiOiJSYW1pZGkiLCJnaXZlbl9uYW1lIjoiQXJ1bmEiLCJpcGFkZHIiOiIyLjEyNS4xNzcuMjE3IiwibmFtZSI6IkFydW5hIFJhbWlkaSIsIm9pZCI6ImJjNzFlMzE1LWNiNzgtNGI1ZC1hODFhLTU0OWFjYTFmNmQyMiIsInB1aWQiOiIxMDAzQkZGREFBNUFFRjg4Iiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwic3ViIjoiakk5TzFnU1pCYzN1ZVNUOVR4d1g4bDRiWEcyc3YyazdiOGlxNGZscVhHZyIsInRpZCI6IjZmNTA0MTEzLTZiNjQtNDNmMi1hZGU5LTI0MmUwNTc4MDAwNyIsInVuaXF1ZV9uYW1lIjoiYXJ1bmEucmFtaWRpQGRlZnJhZGV2Lm9ubWljcm9zb2Z0LmNvbSIsInVwbiI6ImFydW5hLnJhbWlkaUBkZWZyYWRldi5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJ6WGNhekw3Z2FVQzlZT2R1b0pnR0FBIiwidmVyIjoiMS4wIiwid2lkcyI6WyI0NDM2NzE2My1lYmExLTQ0YzMtOThhZi1mNTc4Nzg3OWY5NmEiXX0.oKkGh8IYmwGovPtNI8Bxd7Duh6UUekyNkUrAlrDZ-GVCxruz_X9CrBaDJvqj9DuSdJ6c8XBP_9oXUEQReajt4pTAUGbAaSGuGabuh930027ucOpqWKNaF2O7-YCla7tqDPcjkB25x0eynMhj7XfvO6NsERxrtWS4QyjLB_t6pBRHBVT8voVdYOe3QprT5ILO6gkkAZ3scv3cOrRKa8S5HRdOXMyVj4HHpwSjR_zOT42rGr5hjUBo_vF3bwhS9zKe52g2wkvzLjZEnyS0Ob6Bc-wHcw-WFThxAVmrezsF5WGO911eFAkOGY4zWFgzD4atkcLynab6I6mbKuaD04RJHA";//;
                    this._tokenExpiry = DateTimeOffset.Now.AddHours(1); //
                    //this._token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImlCakwxUmNxemhpeTRmcHhJeGRacW9oTTJZayIsImtpZCI6ImlCakwxUmNxemhpeTRmcHhJeGRacW9oTTJZayJ9.eyJhdWQiOiJodHRwczovL2RlZnJhLWN1c3RtYXN0LWRldi5jcm00LmR5bmFtaWNzLmNvbS8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82ZjUwNDExMy02YjY0LTQzZjItYWRlOS0yNDJlMDU3ODAwMDcvIiwiaWF0IjoxNTI4MDk4NjM2LCJuYmYiOjE1MjgwOTg2MzYsImV4cCI6MTUyODEwMjUzNiwiYWNyIjoiMSIsImFpbyI6IlkyZGdZRGdYZVVsU3dHYW5ZVlJweDU5QTlXY1RHSTY3ekY1aG9KdkpVaEhBL0dpMjcyY0EiLCJhbXIiOlsicHdkIl0sImFwcGlkIjoiMTgwMWQ4M2ItNTRmZi00ZjYzLWJjZmUtOTEzM2E0ZTE2OGZjIiwiYXBwaWRhY3IiOiIwIiwiZV9leHAiOjI2MjgwMCwiZ2l2ZW5fbmFtZSI6IlNBLUVVRS1TVkMiLCJpcGFkZHIiOiI4OS4xNDUuMjAwLjIwMSIsIm5hbWUiOiJTQS1FVUUtU1ZDIiwib2lkIjoiYWI4MGJmY2YtOGNmNy00ZjcwLThkZWQtM2JlYjJkM2MxOWZjIiwicHVpZCI6IjEwMDMzRkZGQUE5Rjk2MjEiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiJINzl5bnpRaXliNk9RTUxnMmgtNVd1U1hzeGExNTFYVVdWai1hZUhVVXVnIiwidGlkIjoiNmY1MDQxMTMtNmI2NC00M2YyLWFkZTktMjQyZTA1NzgwMDA3IiwidW5pcXVlX25hbWUiOiJTQS1FVUUtU1ZDQGRlZnJhZGV2Lm9ubWljcm9zb2Z0LmNvbSIsInVwbiI6IlNBLUVVRS1TVkNAZGVmcmFkZXYub25taWNyb3NvZnQuY29tIiwidXRpIjoiUUpmeWJlZmdJa0NlVGhUMnh5MGlBQSIsInZlciI6IjEuMCJ9.id5dF8ZLF_blSMQRJSnf8OjTi_ljhkRILjo-14LIEEwE9wgnwlDHV89pXK1hlEQ3Nd2ug_LzmCcurq4QqYKpiBg1mMOpR9YqvYv2dbDNEsQhTsAIDpw02pIavDcIs5AbVGHJbAyVidkKKypqwESd_ovQfHu3IESqCN1dDEhIKEn-t8BQDyr3ZDPzmLe9pHSjyyZ537aKph-Dw_XgwUaIQ2ilnbUZHWMZ6qkj7tkQVaqMKHvIB4togwm-b6YWjHLbfscdUoPFe3nhvRK8t5aMtg2f9zdFPlwsrU7xrxcLhYV8_qN36MMBJSt0l1KjdMOf92nkvguvPmqCM00HAeyTxw";//;

                    //this._logger.LogAudit($"Dynamics authentication token refreshed. Token expires at: {this._tokenExpiry} Token: {this._token}");
                }

                return(this._token);
            }
        }
コード例 #5
0
        public HttpClient GetHttpClient()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();

            var configuration = builder.Build();
            var _dynamicsAuthenticationSettingsSection = configuration.GetSection("DynamicsAuthenticationSettings");
            var _dynamicsAuthenticationSettings        = _dynamicsAuthenticationSettingsSection.Get <DynamicsAuthenticationSettings>();

            if (_dynamicsAuthenticationSettings.ActiveEnvironment.ToLower() == "onprem")
            {
                return(getOnPremHttpClient(_dynamicsAuthenticationSettings.OnPremUserName, _dynamicsAuthenticationSettings.OnPremPassword,
                                           _dynamicsAuthenticationSettings.OnPremDomain, _dynamicsAuthenticationSettings.OnPremWebApiUrl));
            }
            else
            {
                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(_dynamicsAuthenticationSettings.CloudResourceUrl)).Result;

                String authorityUrl = ap.Authority;
                String resourceUrl  = ap.Resource;

                return(getOnlineHttpClient(resourceUrl, authorityUrl, _dynamicsAuthenticationSettings.CloudClientId,
                                           _dynamicsAuthenticationSettings.CloudClientSecret, _dynamicsAuthenticationSettings.CloudResourceUrl,
                                           _dynamicsAuthenticationSettings.CloudUserName, _dynamicsAuthenticationSettings.CloudWebApiUrl));
            }
        }
コード例 #6
0
        /// <summary>
        /// Retrieve OAuth and Resource. See https://msdn.microsoft.com/en-us/library/gg327838.aspx for detail
        /// </summary>
        /// <returns>Result</returns>
        public async Task <bool> DiscoveryAuthority()
        {
            // If server url is null, then return false.
            if (String.IsNullOrEmpty(_settings.ServerUrl))
            {
                return(false);
            }

            try
            {
                AuthenticationParameters ap =
                    await AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(_settings.ServerUrl + "/api/data/"));

                _settings.OAuthUrl     = ap.Authority;
                _settings.ResourceName = ap.Resource;

                return(true);
            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog("OAuth Url retrieve failed. Please check Service URL again.");
                await dialog.ShowAsync();

                return(false);
            }
        }
コード例 #7
0
        /// <summary>
        /// Discover the authentication authority asynchronously.
        /// </summary>
        /// <param name="serviceUrl">The specified endpoint address</param>
        /// <returns>The URL of the authentication authority on the specified endpoint address, or an empty string
        /// if the authority cannot be discovered.</returns>
        public static async Task <string> DiscoverAuthorityAsync(string serviceUrl)
        {
            try
            {
                AuthenticationParameters ap = await AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(serviceUrl + "api/data/"));

                return(ap.Authority);
            }
            catch (HttpRequestException e)
            {
                throw new Exception("An HTTP request exception occurred during authority discovery.", e);
            }
            catch (Exception e)
            {
                // These exceptions ocurr when the service is not configured for OAuth.

                // -2147024809 message: Invalid authenticate header format Parameter name: authenticateHeader
                if (e.HResult == -2146233088 || e.HResult == -2147024809)
                {
                    return(String.Empty);
                }
                else
                {
                    throw e;
                }
            }
        }
コード例 #8
0
        public string GetToken(bool moveToken)
        {
            if (string.IsNullOrWhiteSpace(BearerToken) ||
                tokenExpiry < DateTimeOffset.Now.LocalDateTime.AddMinutes(5) ||
                moveToken)
            {
                // Rotate the token index, if it reaches the limit restart the token index counter to 1
                if (moveToken)
                {
                    tokenIdex = (tokenIdex++ <= ClientConfigDictionary.Count) ? tokenIdex : 1;
                }

                string appId  = ClientConfigDictionary[tokenIdex].ClientId;
                string secret = ClientConfigDictionary[tokenIdex].Secret;

                // Get a new D365 bearer token
                AuthenticationParameters authenticationParameters = AuthenticationParameters.CreateFromResourceUrlAsync(resourceUrl: Resource).Result;
                AuthenticationContext    authenticationContext    = new AuthenticationContext(authority: authenticationParameters.Authority, validateAuthority: false);
                ClientCredential         clientCredential         = new ClientCredential(clientId: appId, clientSecret: secret);
                AuthenticationResult     authenticationResult     = authenticationContext.AcquireTokenAsync(resource: authenticationParameters.Resource, clientCredential: clientCredential).Result;

                tokenExpiry = authenticationResult.ExpiresOn.LocalDateTime;
                BearerToken = authenticationResult.AccessToken;
            }

            return(BearerToken);
        }
コード例 #9
0
        internal static async void GetToken(string userId, string password)
        {
            // Get the Resource Url & Authority Url using the Api method. This is the best way to get authority URL
            // for any Azure service api.
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result;

            string resourceUrl  = ap.Resource;
            string authorityUrl = ap.Authority;

            //Generate the Authority context .. For the sake of simplicity for the post, I haven't splitted these
            // in to multiple methods. Ideally, you would want to use some sort of design pattern to generate the context and store
            // till the end of the program.
            authContext = new AuthenticationContext(authorityUrl, false);

            // UserCrendetial object will only accept User Id
            //          starting from the latest version of .NET
            // Thats the reason why we are using UserPasswordCredential
            //         object which is actually inherited by UserCredential.
            UserCredential credentials = new UserPasswordCredential(userId, password);

            //Genertae the AuthToken by using Credentials object.
            authToken = await authContext.AcquireTokenAsync
                            (resourceUrl, clientId, credentials);

            WriteLine("Got the authentication token, Getting data from Webapi !!");

            GetData(authToken.AccessToken);
        }
コード例 #10
0
        public string GetAuthToken(Uri connectedUri)
        {
            var provider    = new AzureServiceTokenProvider(_connectionString);
            var resource    = AuthenticationParameters.CreateFromResourceUrlAsync(connectedUri).Result.Resource;
            var accessToken = provider.GetAccessTokenAsync(resource).Result;

            return(accessToken);
        }
コード例 #11
0
        internal static async Task <AuthenticationParametersProxy> CreateFromResourceUrlAsync(Uri resourceUrl)
        {
            AuthenticationParameters parameters = await AuthenticationParameters.CreateFromResourceUrlAsync(resourceUrl);

            return(new AuthenticationParametersProxy {
                Authority = parameters.Authority, Resource = parameters.Resource
            });
        }
コード例 #12
0
        public static async Task <AuthenticationResult> GetAuthResultAsync(ClientCredential clientCred, string organizationurl, string authparam = DefaultAuthparamValue)
        {
            AuthenticationParameters ap = await AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(organizationurl + (authparam ?? DefaultAuthparamValue))).ConfigureAwait(false);

            var authenticationContext = new AuthenticationContext(ap.Authority, false);

            return(await authenticationContext.AcquireTokenAsync(organizationurl, clientCred).ConfigureAwait(false));
        }
コード例 #13
0
        /// <summary>
        /// Get access token to CDS
        /// </summary>
        /// <param name="clientId">Azure application ID</param>
        /// <param name="userName">User name</param>
        /// <param name="password">Password for provided user name</param>
        /// <returns>AuthenticationResult</returns>
        async Task <AuthenticationResult> GetTokenAsync(string clientId, string userName, string password)
        {
            var authParameters = await AuthenticationParameters.CreateFromResourceUrlAsync(baseAddress);

            var authContext = new AuthenticationContext(authParameters.Authority, false);

            return(await authContext.AcquireTokenAsync(
                       $"{baseAddress.Scheme}://{baseAddress.Authority}",
                       clientId,
                       new UserCredential(userName, password)));
        }
コード例 #14
0
        public override async Task <CrawlJobData> GetCrawlJobData(
            ProviderUpdateContext context,
            IDictionary <string, object> configuration,
            Guid organizationId,
            Guid userId,
            Guid providerDefinitionId)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var sharepointCrawlJobData = new SharePointCrawlJobData();

            if (configuration.ContainsKey(SharePointConstants.KeyName.Url))
            {
                sharepointCrawlJobData.Url = configuration[SharePointConstants.KeyName.Url].ToString();
            }
            if (configuration.ContainsKey(SharePointConstants.KeyName.DeltaCrawlEnabled))
            {
                sharepointCrawlJobData.DeltaCrawlEnabled = bool.Parse(configuration[SharePointConstants.KeyName.DeltaCrawlEnabled].ToString());
            }

            if (configuration.ContainsKey(SharePointConstants.KeyName.UserName))
            {
                sharepointCrawlJobData.UserName = configuration[SharePointConstants.KeyName.UserName].ToString();
            }
            if (configuration.ContainsKey(SharePointConstants.KeyName.Password))
            {
                sharepointCrawlJobData.Password = configuration[SharePointConstants.KeyName.Password].ToString();
            }
            sharepointCrawlJobData.ClientId     = ConfigurationManager.AppSettings.GetValue <string>("Providers.SharePointClientID", null);
            sharepointCrawlJobData.ClientSecret = ConfigurationManager.AppSettings.GetValue <string>("Providers.SharePointClientSecret", null);

            string apiVersion = "9.1";
            string webApiUrl  = $"{sharepointCrawlJobData.Url}/api/data/v{apiVersion}/";

            if (sharepointCrawlJobData.UserName != null && sharepointCrawlJobData.Password != null)
            {
                Crawling.SharePoint.Infrastructure.SharePointClient.RefreshToken(sharepointCrawlJobData);
            }
            else
            {
                var clientCredential = new ClientCredential(sharepointCrawlJobData.ClientId, sharepointCrawlJobData.ClientSecret);
                var authParameters   = await AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(webApiUrl));

                var authContext = new AuthenticationContext(authParameters.Authority);
                var authResult  = authContext.AcquireTokenAsync(authParameters.Resource, clientCredential).Result;
                sharepointCrawlJobData.TargetApiKey = authResult.AccessToken;
            }

            return(await Task.FromResult(sharepointCrawlJobData));
        }
コード例 #15
0
        public OAuthMessageHandler(string serviceUrl, string clientId, string redirectUrl, HttpMessageHandler innerHandler) : base(innerHandler)
        {
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            var ap          = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUrl + "api/data/")).Result;
            var authContext = new AuthenticationContext(ap.Authority, false);

            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            var sendX5C    = new Uri(redirectUrl);
            var authResult = authContext.AcquireTokenAsync(serviceUrl, clientId, sendX5C, null).Result;

            _authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }
コード例 #16
0
        public WhoAmIModel Authenticatate()
        {
            ClientCredential         clientCredential = new ClientCredential(ClientId, ClientSecret);
            AuthenticationParameters authParameters   = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(Dynamics365WebAPIUrl)).Result;
            var authContext = new AuthenticationContext(authParameters.Authority, false);

            AuthenticationResult result = authContext.AcquireTokenAsync(Dynamics365Url, clientCredential).GetAwaiter().GetResult();

            string token = result.AccessToken;

            return(Execute(token));
        }
コード例 #17
0
 public static string DiscoverAuthority(string serviceUrl)
 {
     try
     {
         AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri($"{serviceUrl}api/data/")).Result;
         return(ap.Authority);
     }
     catch (HttpRequestException e)
     {
         throw new Exception("An HTTP request exception occurred during authority discovery.", e);
     }
 }
コード例 #18
0
        public static void RefreshToken(SharePointCrawlJobData sharePointCrawlJobData)
        {
            string apiVersion = "9.1";
            string webApiUrl  = $"{sharePointCrawlJobData.Url}/api/data/v{apiVersion}/";

            var userCredential = new UserCredential(sharePointCrawlJobData.UserName, sharePointCrawlJobData.Password);
            var authParameters = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(webApiUrl)).Result;
            var authContext    = new AuthenticationContext(authParameters.Authority, false);
            var authResult     = authContext.AcquireTokenAsync(authParameters.Resource, sharePointCrawlJobData.ClientId, userCredential).Result;
            var refreshToken   = authContext.AcquireTokenByRefreshTokenAsync(authResult.RefreshToken, sharePointCrawlJobData.ClientId).Result;

            sharePointCrawlJobData.ApiKey = refreshToken.AccessToken;
        }
コード例 #19
0
 public static string DiscoverAuthority(string serviceUrl)
 {
     try
     {
         //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
         AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUrl + "api/data/")).Result;
         return(ap.Authority);
     }
     catch (HttpRequestException e)
     {
         throw new Exception("An HTTP request exception occurred during authority discovery.", e);
     }
 }
コード例 #20
0
        private string GetTokenAsync(Uri api, string clientId, string secretKey)
        {
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(api).Result;

            var creds = new ClientCredential(clientId, secretKey);

            AuthenticationContext context = new AuthenticationContext(ap.Authority);

            var accessToken = context.AcquireTokenAsync(ap.Resource, creds).Result.AccessToken;

            BaseRequest.Token = accessToken;
            return(accessToken);
        }
コード例 #21
0
        public AuthenitcateCaller(string serviceUrl, string clientId, HttpMessageHandler innerHandler, string UserName, string Password, HttpMethod method)
            : base(innerHandler)
        {
            HttpMethod = method;
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                new Uri(serviceUrl + "api/data/")).Result;
            AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);

            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            Task <AuthenticationResult> authResult = authContext.AcquireTokenAsync(serviceUrl, clientId, new UserPasswordCredential(UserName, Password));

            authHeader = new AuthenticationHeaderValue("Bearer", authResult.Result.AccessToken);
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: ajgarg1/WebAPIQuickStart
        static void Main(string[] args)
        {
            // Set these values:
            // e.g. https://yourorg.crm.dynamics.com
            string url = "https://org64c277fb.api.crm8.dynamics.com";
            // e.g. [email protected]
            string userName = "******";
            // e.g. y0urp455w0rd
            string password = "";

            // Azure Active Directory registered app clientid for Microsoft samples
            string clientId = "51f81489-12ee-4a9e-aaae-a2591f45987d";

            var    userCredential = new UserCredential(userName, password);
            string apiVersion     = "9.0";
            string webApiUrl      = $"{url}/api/data/v{apiVersion}/";

            //Authenticate using IdentityModel.Clients.ActiveDirectory
            var authParameters = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(webApiUrl)).Result;
            var authContext    = new AuthenticationContext(authParameters.Authority, false);
            var authResult     = authContext.AcquireToken(url, clientId, userCredential);
            var authHeader     = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(webApiUrl);
                client.DefaultRequestHeaders.Authorization = authHeader;

                // Use the WhoAmI function
                var response = client.GetAsync("WhoAmI").Result;

                if (response.IsSuccessStatusCode)
                {
                    //Get the response content and parse it.
                    JObject body   = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                    Guid    userId = (Guid)body["UserId"];
                    Console.WriteLine("Your UserId is {0}", userId);
                }
                else
                {
                    Console.WriteLine("The request failed with a status of '{0}'",
                                      response.ReasonPhrase);
                }

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
            }
        }
コード例 #23
0
 private void DiscoverAuthority(Uri discoveryUrl)
 {
     try
     {
         Task.Run(async() =>
         {
             var ap     = await AuthenticationParameters.CreateFromResourceUrlAsync(discoveryUrl);
             _resource  = ap.Resource;
             _authority = ap.Authority;
         }).Wait();
     }
     catch (Exception e)
     {
         throw e;
     }
 }
コード例 #24
0
        private AuthenticationResult GetAccessTokenFromAzureAD(Uri orgUrl)
        {
            var clientSecret = CryptoManager.Decrypt(_connection.S2SClientSecret, ConnectionManager.CryptoPassPhrase,
                                                     ConnectionManager.CryptoSaltValue,
                                                     ConnectionManager.CryptoHashAlgorythm,
                                                     ConnectionManager.CryptoPasswordIterations,
                                                     ConnectionManager.CryptoInitVector,
                                                     ConnectionManager.CryptoKeySize);

            var credentials = new ClientCredential(_connection.AzureAdAppId.ToString(), clientSecret);
            var parameters  = AuthenticationParameters.CreateFromResourceUrlAsync(orgUrl).Result;
            var context     = new AuthenticationContext(parameters.Authority);
            var result      = context.AcquireToken(parameters.Resource, credentials);

            return(result);
        }
コード例 #25
0
        private async Task DiscoveryAuthority2(string serviceUrl)
        {
            try
            {
                //AuthenticationParameters t = await AuthenticationParameters.CreateFromResourceUrlAsync(
                //    new Uri(serviceUrl + "/api/data/"));
                this.ap = await AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(serviceUrl + "/api/data/")).ConfigureAwait(false);

                string s = "";
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #26
0
        static void Main(string[] args)
        {
            var    crmBaseUrl    = "https://xxxxxxxx.crm.dynamics.com/api/data/V8.2/";
            string applicationId = "23b056d1-0351-4346-9727-f12195b1a2c6";                //set to the application ID of your Azure Application
            string clientSecret  = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="; //set to the value of the key you created for your application

            //retrieve authority url and resource
            //and then get the authentication token
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(crmBaseUrl)).Result;

            Console.WriteLine($"Authority: {ap.Authority}");
            Console.WriteLine($"Resouce: {ap.Resource}");

            AuthenticationContext       authContext = new AuthenticationContext(ap.Authority, false);
            Task <AuthenticationResult> taskResult  = authContext.AcquireTokenAsync(ap.Resource, new ClientCredential(applicationId, clientSecret));
            AuthenticationResult        result      = taskResult.Result;

            string getAccountsWithNameContainingMicrosoft = $"{crmBaseUrl}accounts?$select=name&$filter=contains(name,%20%27Microsof%27)&$orderby=name%20desc&$top=10";

            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes
                string authorizationHeader = result.CreateAuthorizationHeader();
                httpClient.DefaultRequestHeaders.Add("Authorization", authorizationHeader);

                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, getAccountsWithNameContainingMicrosoft);
                req.Method = HttpMethod.Get;

                // Wait for the web service response.
                HttpResponseMessage response;
                response = httpClient.SendAsync(req).Result;
                if (response.IsSuccessStatusCode)
                {
                    var responseBodyAsText = response.Content.ReadAsStringAsync().Result;

                    Console.WriteLine(responseBodyAsText);
                }
                else
                {
                    Console.WriteLine(response.StatusCode + Environment.NewLine + response.ReasonPhrase);
                }
            }

            Console.WriteLine();
            Console.WriteLine("Done!");
            Console.ReadLine();
        }
コード例 #27
0
        /// <summary>
        /// Discover the authentication authority.
        /// </summary>
        /// <param name="serviceUrl">The URL of the CRM server root address. For example: https://mydomain.crm.dynamics.com</param>
        public void DiscoverAuthority(String serviceUrl)
        {
            try
            {
                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUrl + "/api/data/")).Result;

                if (!String.IsNullOrEmpty(ap.Resource))
                {
                    _service = ap.Resource;
                }
                _authority = ap.Authority;
            }
            catch (HttpRequestException e)
            {
                throw new Exception("An HTTP request exception occurred during authority discovery.", e);
            }
        }
コード例 #28
0
        internal static async void GetToken()
        {
            try
            {
                // Get the Resource Url & Authority Url using the Api method. This is the best way to get authority URL
                // for any Azure service api.
                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result;

                string resourceUrl  = ap.Resource;
                string authorityUrl = ap.Authority;

                //Generate the Authority context .. For the sake of simplicity for the post, I haven't splitted these
                // in to multiple methods. Ideally, you would want to use some sort of design pattern to generate the context and store
                // till the end of the program.
                authContext = new AuthenticationContext(authorityUrl, false);

                try
                {
                    //Check if we can get the authentication token w/o prompting for credentials.
                    //With this system will try to get the token from the cache if there is any, if it is not there then will throw error
                    authToken = await authContext.AcquireTokenAsync(resourceUrl, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Never));
                }
                catch (AdalException e)
                {
                    if (e.ErrorCode == "user_interaction_required")
                    {
                        // We are here means, there is no cached token, So get it from the service.
                        // You should see a prompt for User Id & Password at this place.
                        authToken = await authContext.AcquireTokenAsync(resourceUrl, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Auto));
                    }
                    else
                    {
                        throw;
                    }
                }

                WriteLine("Got the authentication token, Getting data from Webapi !!");

                GetData(authToken.AccessToken);
            }
            catch (Exception ex)
            {
                WriteLine($"Some thing unexpected happened here, Please see the exception details : {ex.ToString()}");
            }
        }
コード例 #29
0
        private AuthenticationResult GetAccessTokenFromAzureAD(Uri orgUri)
        {
            // Get the settings from host.json
            string appID      = ConfigurationManager.AppSettings["ScantegraAutomationAppID"];
            string secretyKey = ConfigurationManager.AppSettings["ScantegraAutomationAppKey"];

            ClientCredential         clientCredential         = new ClientCredential(appID, secretyKey);
            AuthenticationParameters authenticationParameters = AuthenticationParameters.CreateFromResourceUrlAsync(orgUri).Result;

            string authorityUrl = authenticationParameters.Authority;
            string resourceUrl  = authenticationParameters.Resource;

            AuthenticationContext authenticationContext = new AuthenticationContext(authorityUrl);

            AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(resourceUrl, clientCredential).Result;

            return(authenticationResult);
        }
コード例 #30
0
        public OAuthMessageHandler(string url, string clientId, string username, string password, HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.

            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(url + "/api/data/v9.1/")).Result;

            AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);

            ClientCredential credential = new ClientCredential("fe4c5bad-24a7-433a-a523-318a435ad676", "n3eIliUcxnEzRLu**G0Z3n.@xCys6kKC");

            string authorityUri = "https://login.microsoftonline.com/2c55b088-a14f-4c9e-8a12-c13454aa56dd/oauth2/authorize";

            AuthenticationContext context = new AuthenticationContext(authorityUri);
            var authResult = context.AcquireTokenAsync("https://cggtech.crm.dynamics.com", credential);

            authHeader = new AuthenticationHeaderValue("Bearer", authResult.Result.AccessToken);
        }