Ejemplo n.º 1
2
 /// <summary>
 /// Retrieves a new auth token from AAD.
 /// </summary>
 /// <param name="authUrl">The root of the authority url.</param>
 /// <param name="tenantDomain">The domain name of the Azure tenant as the second part of the authority url.</param>
 /// <param name="targetServiceUrl">The url of the service that should be accessed. Be sure to check trailing slashes!</param>
 /// <param name="clientId">The unique client id as it is configured in Azure Portal.</param>
 /// <param name="appKey">This value is optional and contains the App-Key-Secret if it is configured in azure portal.</param>
 /// <param name="redirectUrl">The redirect url as it is configured in Azure Portal.</param>
 /// <returns>The authentication token.</returns>
 public static async Task<string> RetrieveTokenAsync(string authUrl, string tenantDomain, string targetServiceUrl, string clientId, Uri redirectUrl, string appKey = null)
 {
     var authenticationContext = new AuthenticationContext($"{authUrl}/{tenantDomain}");
     try
     {
         AuthenticationResult result = null;                
         if (appKey.IsNullOrEmpty())
         {
             // use user auth
             var parameters = new PlatformParameters(PromptBehavior.Auto);
             result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientId, redirectUrl, parameters).ConfigureAwait(false);
         }
         else
         {
             // use key auth
             var clientCredential = new ClientCredential(clientId, appKey);
             result = await authenticationContext.AcquireTokenAsync(targetServiceUrl, clientCredential).ConfigureAwait(false);
         }
         if (result == null)
         {
             throw new InvalidOperationException("Failed to obtain the JWT token");
         }
         // store token for reuse
         return result.AccessToken;
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException("Could not retrieve token.", ex);
     }
 }
Ejemplo n.º 2
1
 /// <summary>
 /// Get Token for Application.
 /// </summary>
 /// <returns>Token for application.</returns>
 public static string GetTokenForApplication(string tenantName, string clientId, string clientSecret)
 {
     AuthenticationContext authenticationContext = new AuthenticationContext(String.Format(Constants.AuthString, tenantName), false);
     // Config for OAuth client credentials 
     ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
     Task<AuthenticationResult> authenticationResult = authenticationContext.AcquireTokenAsync(Constants.ResourceUrl, clientCred);
     string token = authenticationResult.Result.AccessToken;
     return token;
 }
        public async Task JsonWebTokenWithX509PublicCertSendX5CTestAsync()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate);
            var context         = new AuthenticationContext(TestConstants.TenantSpecificAuthority, new TokenCache());

            var validCertClaim = "\"x5c\":\"" + Convert.ToBase64String(certificate.GetRawCertData());

            //Check for x5c claim
            HttpMessageHandlerFactory.AddMockHandler(X5CMockHandler);
            AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(X5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            //Check for empty x5c claim
            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            context.TokenCache.Clear();
            result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, false).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, false).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);
        }
Ejemplo n.º 4
0
        public async Task<string> Login(string sharePointSiteUrl, bool forceLogin = false)
        {
            var spUri = new Uri(sharePointSiteUrl);

            string resourceUri = spUri.Scheme + "://" + spUri.Authority;

            ADAL.AuthenticationResult authenticationResult;
 
            try
            {
                authenticationResult = await AuthContext.AcquireTokenSilentAsync(resourceUri, clientId);
            }
            catch (ADAL.AdalSilentTokenAcquisitionException)
            {
                //Console.WriteLine("Silent Async failed. Use prompt instead.");

                try
                {
                    // prevent flashing of login window when credentials are valid
                    var authParam = new ADAL.PlatformParameters(ADAL.PromptBehavior.Never);
                    authenticationResult = await AuthContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), authParam);
                }
                catch (ADAL.AdalException /* e */)
                {
                    //Console.WriteLine(e);

                    var authParam = new ADAL.PlatformParameters(ADAL.PromptBehavior.Auto);
                    authenticationResult = await AuthContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), authParam);

                }
            }


            return authenticationResult.CreateAuthorizationHeader();
        }
Ejemplo n.º 5
0
      /// <summary>
      /// Gets the access token
      /// </summary>
      /// <param name="authority"> Authority </param>
      /// <param name="resource"> Resource </param>
      /// <param name="scope"> scope </param>
      /// <returns> token </returns>
      public async Task<string> GetAccessToken(string authority, string resource, string scope)
      {
         var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
         var result = await context.AcquireTokenAsync(resource, _credential);

         return result.AccessToken;
      }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            /// Azure AD WebApi's APP ID URL
            string resource = "";

            /// Azure AD WebApi's Client ID
            string clientId = "";

            /// Azure AD User's credentials
            string userName     = "";
            string userPassword = "";

            /// Web API's URL
            string apiUrl = "http://localhost:3672/api/Test";

            var user = new UserCredential(userName, userPassword);

            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");

            /// Get an Access Token to Access the Web API on behalf of the user
            AuthenticationResult authResult = authContext.AcquireTokenAsync(resource, clientId, user).Result;

            /// Call WebAPI passing Access token on header
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            /// Get the result
            HttpResponseMessage response = client.GetAsync(apiUrl).Result;
            string text = response.Content.ReadAsStringAsync().Result;
        }
        public async Task AcquireTokenWithValidTokenInCache_ReturnsCachedTokenAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
            };

            var result = await context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                         new UserPasswordCredential(TestConstants.DefaultDisplayableId, TestConstants.DefaultPassword)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("existing-access-token", result.AccessToken);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.IsNotNull(result.UserInfo);

            // There should be one cached entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
        public void UserRealmDiscoveryFailsTest()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/" + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Bad request received")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            var ex = AssertException.TaskThrows <AdalException>(() =>
                                                                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                          new UserPasswordCredential(TestConstants.DefaultDisplayableId,
                                                                                                                     TestConstants.DefaultPassword)));

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
            Assert.AreEqual(0, context.TokenCache.Count);

            //To be addressed in a later fix
            //Assert.AreEqual(((AdalException)ex.InnerException.InnerException).ErrorCode, AdalError.UserRealmDiscoveryFailed);
        }
        public async Task UnknownUserRealmDiscoveryTestAsync()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant);
            await context.Authenticator.UpdateFromTemplateAsync(null).ConfigureAwait(false);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/" + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Unknown\",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            var ex = AssertException.TaskThrows <AdalException>(() =>
                                                                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                          new UserPasswordCredential(TestConstants.DefaultDisplayableId,
                                                                                                                     TestConstants.DefaultPassword)));

            Assert.AreEqual(AdalError.UnknownUserType, ex.ErrorCode);
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
            Assert.AreEqual(0, context.TokenCache.Count);
        }
Ejemplo n.º 10
0
        private async Task AddRoles(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
        {
            var context           = new Adal.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
            var clientCredentials = new Adal.ClientCredential(GraphClientId, GraphClientSecret);
            var token             = await context.AcquireTokenAsync("https://graph.windows.net/", clientCredentials);

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

            HttpClient http = new HttpClient();
            string     url  = "https://graph.windows.net/b2ctestdes.onmicrosoft.com/users/" + userId + "/memberOf?api-version=1.6";

            // Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
            HttpResponseMessage response = await http.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                dynamic groups = JObject.Parse(result);

                foreach (var group in groups.value)
                {
                    string groupName = group.displayName;

                    arg.AuthenticationTicket.Identity.AddClaim(
                        new Claim(ClaimTypes.Role, groupName));
                }
            }
        }
         /// <summary>
        /// Get the access token
        /// </summary>
        /// <param name="clientId">Client ID of the Web API app</param>
        /// <param name="appKey">Client secret for the Web API app</param>
        /// <param name="aadInstance">The login URL for AAD</param>
        /// <param name="tenant">Your tenant (eg kirke.onmicrosoft.com)</param>
        /// <param name="resource">The resource being accessed
           ///(eg., https://rbinrais.sharepoint.com)
        /// </param>
        /// <returns>string containing the access token</returns>
        public static async Task<string> GetAccessToken(
            string clientId,
            string appKey,
            string aadInstance,
            string tenant,
            string resource)
        {
            string accessToken = null;
            AuthenticationResult result = null;
 
 
            ClientCredential clientCred = new ClientCredential(clientId, appKey);
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];
 
            string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
            UserAssertion userAssertion = new UserAssertion(userAccessToken);
 
            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
 
            AuthenticationContext authContext = new AuthenticationContext(authority);

            result = await authContext.AcquireTokenAsync(resource, clientCred, userAssertion);
            accessToken = result.AccessToken;
 
            return accessToken;
        }
        public async Task JsonWebTokenWithX509PublicCertClaimTest()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate);
            var context         = new AuthenticationContext(TestConstants.TenantSpecificAuthority, new TokenCache());

            var validCertClaim = "\"x5c\":\"" + Convert.ToBase64String(certificate.GetRawCertData());

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.TenantSpecificAuthority))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"access_token\":\"some-access-token\"}")
                },
                AdditionalRequestValidation = request =>
                {
                    var requestContent = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    var formsData      = EncodingHelper.ParseKeyValueList(requestContent, '&', true, null);

                    // Check presence of client_assertion in request
                    string encodedJwt;
                    Assert.IsTrue(formsData.TryGetValue("client_assertion", out encodedJwt), "Missing client_assertion from request");

                    // Check presence of x5c cert claim. It should not exist.
                    var jwtHeader = EncodingHelper.UrlDecode(encodedJwt.Split('.')[0]);
                    Assert.IsTrue(!jwtHeader.Contains("\"x5c\":"));
                }
            });

            AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion);

            Assert.IsNotNull(result.AccessToken);
        }
        public async Task AutoPromptBehaviorWithTokenInCacheTestAsync()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
            };

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual("existing-access-token", result.AccessToken);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Ejemplo n.º 14
0
 private static async Task<string> GetAccessToken(X509Certificate2 certificate)
 {
     var authenticationContext = new AuthenticationContext(Authority, false);
     var cac = new ClientAssertionCertificate(ClientId, certificate);
     var authenticationResult = await authenticationContext.AcquireTokenAsync(GraphUrl, cac);
     return authenticationResult.AccessToken;
 }
Ejemplo n.º 15
0
        private async void Authenticate()
        {
            var authConfig = App.AuthenticationConfiguration;
            var authContext = new AuthenticationContext("https://login.windows.net/" + authConfig.DirectoryDomain);

            //Use this during development if you don't want your credentials cached
            //authContext.TokenCacheStore.Clear();

            var result = await authContext.AcquireTokenAsync(authConfig.AppRedirectUri, authConfig.AppClientId, new Uri(authConfig.ApiAppSignOnUrl));

            if (result.Status == AuthenticationStatus.Success)
            {
                App.BearerToken = result.AccessToken;
                App.CurrentUser = result.UserInfo;

                //Here is how to make a secure HTTP call with SecureHttpClient
                //var secureHttpClient = new SecureHttpClient(result.AccessToken);
                //var resp = await secureHttpClient.GetAsync("http://localhost:3184/api/echo?whoami=true");

                var rootFrame = (Frame)Window.Current.Content;
                rootFrame.Navigate(typeof(Views.Menu.MenuPage));
            }
            else
            {
                Authenticate();
            }
        }
        static void Main(string[] args)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

            ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
            var authenticationContext         = new AuthenticationContext(authorityUriv2, true);
            var authContext          = new AuthenticationContext(authorityUriv2);
            var authenticationResult = authContext.AcquireTokenAsync(resource, clientId, new Uri(ClientRedirectUrl), new PlatformParameters(PromptBehavior.Auto)).GetAwaiter().GetResult();

            accessToken = authenticationResult.AccessToken;

            //var clientBC = new RestClient("https://api.businesscentral.dynamics.com/v2.0/Production/api/CertTech/Integrations/v1.0");
            var clientBC = new RestClient("https://api.businesscentral.dynamics.com/v2.0/Production/api/CertTech/Integrations/v1.0/companies");

            clientBC.Timeout = -1;
            var requestBC = new RestRequest(Method.GET);

            requestBC.AddHeader("Authorization", "Bearer " + accessToken);
            IRestResponse responseBC = clientBC.Execute(requestBC);

            bcResponse = responseBC.Content;
            object resposeDataBC = JsonConvert.DeserializeObject(bcResponse);

            Console.Write(resposeDataBC);
            Console.ReadKey();
        }
        private async Task <AuthenticationResult> GetAppOnlyAccessToken(string resource, string tenantId)
        {
            string authority = appConfig.AuthorizationUri.Replace("common", tenantId);

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(
                authority,
                false);

            string certfile = Server.MapPath(appConfig.ClientCertificatePfx);

            X509Certificate2 cert = new X509Certificate2(
                certfile,
                appConfig.ClientCertificatePfxPassword,
                X509KeyStorageFlags.MachineKeySet);

            // ADAL new ... (in Beta, might change)
            // ClientAssertionCertificate cac = new ClientAssertionCertificate(
            //    appConfig.ClientId,
            //    cert.GetRawCertData(),
            //    appConfig.ClientCertificatePfxPassword);

            // ADAL current released (2.12.111071459)
            ClientAssertionCertificate cac = new ClientAssertionCertificate(
                appConfig.ClientId, cert);

            var authenticationResult = await authenticationContext.AcquireTokenAsync(
                resource,
                cac);

            return(authenticationResult);
        }
        public async Task AutoPromptBehaviorTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"));

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>()
                {
                    { "grant_type", "authorization_code" }
                }
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());
            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Auto)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);
            // There should be one cached entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Ejemplo n.º 19
0
        static async Task MainAsync(string[] args)
        {
            var keyClient = new KeyVaultClient(async (authority, resource, scope) =>
            {
                var adCredential = new ClientCredential(applicationId, applicationSecret);
                var authenticationContext = new AuthenticationContext(authority, null);
                return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
            });

            // Get the key details
            var keyIdentifier = "https://rahulkeyvault.vault.azure.net:443/keys/NewKey";
            var key = await keyClient.GetKeyAsync(keyIdentifier);
            var publicKey = Convert.ToBase64String(key.Key.N);

            using (var rsa = new RSACryptoServiceProvider())
            {
                var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
                rsa.ImportParameters(p);
                var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
                
                // Encrypt and Decrypt
                var encryptedText = rsa.Encrypt(byteData, true);
                var decryptedData = await keyClient.DecryptAsync(keyIdentifier, "RSA-OAEP", encryptedText);
                var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);

                // Sign and Verify
                var hasher = new SHA256CryptoServiceProvider();
                var digest = hasher.ComputeHash(byteData);
                var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
                var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
            }
        }
        public void ForcePromptForNeverPromptBehaviorTest()
        {
            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, new TokenCache());

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                                                  TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                  TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId);

            context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow)
            };

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage()
            });

            var exc = AssertException.TaskThrows <AdalServiceException>(() =>
                                                                        context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                                                                                  TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.Never)));

            Assert.AreEqual(AdalError.FailedToRefreshToken, exc.ErrorCode);
            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Ejemplo n.º 21
0
        private async Task AdalLogin(bool forcePrompt)
        {
            var spUri = new Uri($"{txtSiteFor2FA.Text}");

            string       resourceUri = spUri.Scheme + "://" + spUri.Authority;
            const string clientId    = "9bc3ab49-b65d-410a-85ad-de819febfddc";
            const string redirectUri = "https://oauth.spops.microsoft.com/";

            ADAL.AuthenticationResult authenticationResult;

            if (authContext == null || forcePrompt)
            {
                ADAL.TokenCache cache = new ADAL.TokenCache();
                authContext = new ADAL.AuthenticationContext(AuthorityUri, cache);
            }
            try
            {
                if (forcePrompt)
                {
                    throw new ADAL.AdalSilentTokenAcquisitionException();
                }
                authenticationResult = await authContext.AcquireTokenSilentAsync(resourceUri, clientId);
            }
            catch (ADAL.AdalSilentTokenAcquisitionException)
            {
                authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always, null), ADAL.UserIdentifier.AnyUser, null, null);
            }

            options.AccessToken = authenticationResult.AccessToken;
            accessTokenObtained = true;
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            /// Azure AD WebApi's APP ID URL
            string resource = "";

            /// Azure AD WebApi's Client ID 
            string clientId = "";

            /// Azure AD User's credentials
            string userName = "";
            string userPassword = "";

            /// Web API's URL
            string apiUrl = "http://localhost:3672/api/Test";

            var user = new UserCredential(userName, userPassword);

            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");

            /// Get an Access Token to Access the Web API on behalf of the user
            AuthenticationResult authResult = authContext.AcquireTokenAsync(resource, clientId, user).Result;

            /// Call WebAPI passing Access token on header
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            /// Get the result 
            HttpResponseMessage response = client.GetAsync(apiUrl).Result;
            string text = response.Content.ReadAsStringAsync().Result;
        }
Ejemplo n.º 23
0
    /// <summary>
    /// get crm service client
    /// </summary>
    public void GetCrmServiceClient()
    {
        if (string.IsNullOrWhiteSpace(this.crmConnection))
        {
            this.ReadKeyVault();
        }

        try
        {
            var credentials = new ClientCredential(this.appClientID, this.appClientSecret);
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(this.authority);
            var result = authContext.AcquireTokenAsync(this.resourceURL, credentials).Result;
            var accesToken = result.AccessToken;
            Uri serviceUrl = new Uri(this.CRMConnection);

            using (sdkService = new OrganizationWebProxyClient(serviceUrl, false))
            {
                sdkService.HeaderToken = accesToken;

                this.ServiceClient = (IOrganizationService)sdkService != null ? (IOrganizationService)sdkService : null;
            }

        }
        catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
        {
            this.logger.Error("CRM Connection Issue: ", ex);
            throw;
        }
        catch (Exception ex)
        {
            this.logger.Error("CRM Connection Issue: ", ex);
            throw;
        }
    }
        public ICustomActivityResult Execute()
        {
            string Message               = string.Empty;
            string authContextURL        = "https://login.windows.net/" + tenantId;
            var    authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authContextURL);
            var    credential            = new ClientCredential(clientId, clientSecret);
            var    result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;

            if (result == null)
            {
                Message = "Failed to obtain the JWT token";
                return(this.GenerateActivityResult(Message));
            }
            string         token   = result.AccessToken;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Compute/snapshots/" + snapshotName + "?api-version=2018-06-01");

            request.Method = "DELETE";
            request.Headers["Authorization"] = "Bearer " + token;
            request.ContentType = "application/json";
            try
            {
                request.GetRequestStream();
                var httpResponse = (HttpWebResponse)request.GetResponse();
                httpResponse.GetResponseStream();
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                return(this.GenerateActivityResult(Message));
            }
            Message = "Success";
            return(this.GenerateActivityResult(Message));
        }
Ejemplo n.º 25
0
        public async Task <string> GetAccessTokenAdal()
        {
            var creds = new Adal.ClientCredential(CLIENT_ID, CLIENT_SECRET);
            var ctx   = new Adal.AuthenticationContext($"https://login.microsoftonline.com/{TENANT_ID}", false);
            var token = await ctx.AcquireTokenAsync("https://database.windows.net/", creds);

            return(token.AccessToken);
        }
Ejemplo n.º 26
0
        public static string GetToken(string clientId, string clientSecret, string authority, string resourceUrl)
        {
            ClientCredential credentials = new ClientCredential(clientId, clientSecret);
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
            var result      = authContext.AcquireTokenAsync(resourceUrl, credentials).Result;

            return(result.AccessToken);
        }
        public static async Task <string> GetTokenWeb(RuntimeOptions runtimeOptions)
        {
            // Get OAuth token using client credentials
            string tenantName = runtimeOptions.tenantName;

            string authString = runtimeOptions.authUrl + "/" + tenantName;

            authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authString, false);

            string token;

            try
            {
                AuthenticationResult authenticationResult = null;
                if (runtimeOptions.cert == null)
                {
                    ClientCredential clientCred = new ClientCredential(runtimeOptions.clientId, runtimeOptions.key);
                    authenticationResult = await authenticationContext.AcquireTokenAsync(runtimeOptions.resource, clientCred);
                }
                else
                {
                    ClientAssertionCertificate clientCert = new ClientAssertionCertificate(runtimeOptions.clientId, runtimeOptions.cert);
                    authenticationResult = await authenticationContext.AcquireTokenAsync(runtimeOptions.resource, clientCert);
                }

                token = authenticationResult.AccessToken;
                return(token);
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //  You should implement retry and back-off logic according to
                    //  http://msdn.microsoft.com/en-us/library/dn168916.aspx . This topic also
                    //  explains the HTTP error status code in the InnerException message.
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
        public static async Task <string> GetAccessToken(string azureTenantId, string clientId, string redirectUri)
        {
            var context     = new AuthenticationContext("https://login.windows.net/" + tenantId);
            var credential  = new ClientCredential(appId, appSecret);
            var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", credential);

            return(tokenResult.AccessToken);
        }
Ejemplo n.º 29
0
        private async Task <AuthenticationResult> GetTokenForPBIEmbedded()
        {
            UserPasswordCredential credentials = new UserPasswordCredential(username, password);

            var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);

            return(await authenticationContext.AcquireTokenAsync(pbiApiResourceUrl, clientId, credentials));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Authentication callback that gets a token using the X509 certificate
        /// </summary>
        /// <param name="authority">Address of the authority</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token</param>
        /// <param name="scope">Scope</param>
        /// <param name="assertionCert">The assertion certificate</param>
        /// <returns> The access token </returns>
        public static async Task<string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate assertionCert)
        {
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

            var result = await context.AcquireTokenAsync(resource, assertionCert);

            return result.AccessToken;
        }
Ejemplo n.º 31
0
        public static AuthenticationResult GetAzureAdToken(AuthenticationContext authContext, String resourceHostUri,
            string clientId, string redirectUri, UserCredential uc)
        {
            AuthenticationResult authenticationResult = null;

            Console.WriteLine("Performing GetAzureAdToken");
            try
            {
                Console.WriteLine("Passed resource host URI is " + resourceHostUri);
                if (resourceHostUri.StartsWith("http"))
                {
                    resourceHostUri = Helpers.ReduceUriToProtoAndHost(resourceHostUri);
                    Console.WriteLine("Normalized the resourceHostUri to just the protocol and hostname " + resourceHostUri);
                }

                // check if there's a user credential - i.e. a username and password

                if(uc != null)
                    {
                    authenticationResult = authContext.AcquireTokenAsync(resourceHostUri, clientId, uc).Result;

                }
                else {
                    PlatformParameters platformParams = new PlatformParameters(PromptBehavior.Auto);
                    authenticationResult = authContext.AcquireTokenAsync(resourceHostUri, clientId, new Uri(redirectUri), platformParams).Result;
                }

                //Console.WriteLine("Bearer token from Azure AD is " + authenticationResult.AccessToken);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("An unexpected error occurred.");
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += Environment.NewLine + "Inner Exception : " + ex.InnerException.Message;
                }
                Console.WriteLine("Message: {0}", message);
                Console.ForegroundColor = ConsoleColor.White;

            }

            return authenticationResult;
        }
Ejemplo n.º 32
0
        private static async Task <Adalv2.AuthenticationResult> AcquireAadToken(string audience)
        {
            var authority   = GetAuthority(audience);
            var credential  = new Adalv2.ClientCredential(Config.InternalUsersClientId, Config.InternalUsersClientSecret);
            var authContext = new Adalv2.AuthenticationContext(authority);
            var result      = await authContext.AcquireTokenAsync(Config.InternalUsersClientId, credential);

            return(result);
        }
Ejemplo n.º 33
0
        private async Task <string> GetTokenAsync()
        {
            var resourceID  = $"https://{config.Region}.asazure.windows.net";
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($"https://login.windows.net/{config.TenantId}");
            ClientCredential     credential = new ClientCredential(config.ClientId, config.ClientSecret);
            AuthenticationResult token      = await authContext.AcquireTokenAsync(resourceID, credential).ConfigureAwait(false);

            return(token.AccessToken); //Use this token to connect to AAS.
        }
Ejemplo n.º 34
0
        public async Task<AuthenticationResult> GetToken(string resource)
        {
            ClientAssertionCertificate cac = GetClientAssertionCertificate();

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority);
            AuthenticationResult authResult = await authContext.AcquireTokenAsync(resource, cac);

            return authResult;
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Gets an access token for the client ID and client key specified in the configuration.
        /// </summary>
        /// <param name="authority">The authority granting access.</param>
        /// <param name="resource">The resource to access.</param>
        /// <param name="scope">The scope of the authentication request.</param>
        /// <returns>An access token.</returns>
        public static async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            ClientCredential credential = new ClientCredential(CloudConfigurationManager.GetSetting("KVClientId"), CloudConfigurationManager.GetSetting("KVClientKey"));

            AuthenticationContext ctx = new AuthenticationContext(new Uri(authority).AbsoluteUri, false);
            AuthenticationResult result = await ctx.AcquireTokenAsync(resource, credential);

            return result.AccessToken;
        }
Ejemplo n.º 36
0
        private string AcquireToken(string resourceURI, string authority, string clientId, string clientSecret, string redirectUrl, string userName)
        {
            var clientCredential = new ClientCredential(clientId, clientSecret);
            AuthenticationContext authContext =
                new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false);
            AuthenticationResult result = authContext.AcquireTokenAsync(resourceURI, clientCredential).Result;

            return(result.AccessToken);
        }
        public async Task ForcePromptForSelectAccountPromptBehaviorTestAsync()
        {
            MockHelpers.ConfigureMockWebUI(new AuthorizationResult(AuthorizationStatus.Success,
                                                                   TestConstants.DefaultRedirectUri + "?code=some-code"),
                                           // validate that authorizationUri passed to WebUi contains prompt=select_account query parameter
                                           new Dictionary <string, string> {
                { "prompt", "select_account" }
            });

            var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache());

            await context.TokenCache.StoreToCacheAsync(new AuthenticationResultEx
            {
                RefreshToken       = "some-rt",
                ResourceInResponse = TestConstants.DefaultResource,
                Result             = new AuthenticationResult("Bearer", "existing-access-token",
                                                              DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100))
                {
                    UserInfo =
                        new UserInfo()
                    {
                        DisplayableId = TestConstants.DefaultDisplayableId,
                        UniqueId      = TestConstants.DefaultUniqueId
                    }
                },
            },
                                                       TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User,
                                                       new CallState(new Guid())).ConfigureAwait(false);

            ResetInstanceDiscovery();

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityHomeTenant))
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(),
                PostData        = new Dictionary <string, string>
                {
                    { "grant_type", "authorization_code" }
                }
            });

            AuthenticationResult result =
                await
                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId,
                                          TestConstants.DefaultRedirectUri, new PlatformParameters(PromptBehavior.SelectAccount)).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, context.Authenticator.Authority);
            Assert.AreEqual("some-access-token", result.AccessToken);
            Assert.IsNotNull(result.UserInfo);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.UserInfo.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.UserInfo.UniqueId);

            // There should be only one cache entry.
            Assert.AreEqual(1, context.TokenCache.Count);
        }
Ejemplo n.º 38
0
        private async Task <ServiceClientCredentials> GetCredentials(string tenantId, string clientId, string clientSecret)
        {
            var context    = new AD.AuthenticationContext($"https://login.windows.net/{tenantId}");
            var credential = new AD.ClientCredential(clientId, clientSecret);
            var result     = await context.AcquireTokenAsync("https://management.core.windows.net/", credential);

            string token = result.CreateAuthorizationHeader().Substring("Bearer ".Length);

            return(new TokenCredentials(token));
        }
        private static static async Task <string> GetAccessToken(string azureTenantId, string azureAppId, string azureSecretKey)
        {
            var context          = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($"https://login.windows.net/{_tenantId}");
            var clientCredential = new ClientCredential(_appId, _appSecret);
            var tokenResponse    = await context.AcquireTokenAsync("https://vault.azure.net", clientCredential);

            var accessToken = tokenResponse.AccessToken;

            return(accessToken);
        }
        /// <summary>
        /// Authenticate using the credentials stored for the given client id
        /// </summary>
        /// <param name="clientId">The Application ID for this service principal</param>
        /// <param name="audience">The intended audicne for authentication</param>
        /// <param name="context">The AD AuthenticationContext to use</param>
        /// <returns></returns>
        public async Task<AuthenticationResult> AuthenticateAsync(string clientId, string audience, AuthenticationContext context)
        {
            if (_credentials.ContainsKey(clientId))
            {
                var creds = _credentials[clientId];
                return await context.AcquireTokenAsync(audience, creds);
            }

            throw new AuthenticationException("Matching credentials for client id '{0}' could not be found.");
        }
Ejemplo n.º 41
0
        public static void Main(string[] args)
        {
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ctx = GetAuthenticationContext(null);
            AuthenticationResult result         = null;
            IPlatformParameters  promptBehavior = new PlatformParameters(PromptBehavior.Auto);

            try
            {
                //PromptBehavior.RefreshSession will enforce an authn prompt every time. NOTE: Auto will take your windows login state if possible
                result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, new Uri(replyUri), promptBehavior).Result;
                Console.WriteLine("Token expires on: " + result.ExpiresOn);

                var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                helper.ListRepos(bearerAuthHeader, "HR-TAL");

                //Collect Branches for Repo
                int counter = 0;
                //helper.RepoList.ForEach(r =>
                //{
                //    Console.WriteLine(String.Format("Processing repo {0} > {1}", ++counter, r.name));
                //    helper.ListBranchesForRepo(r);
                //    helper.ListBuildsForRepoBranch(r, "refs/heads/master");
                //});
                Console.WriteLine("Fetching all releases as per specified filters...");
                helper.ListReleases(bearerAuthHeader, "HR-");
                Console.WriteLine("--------------------------------------------------");
                DumpCSV();
                Console.WriteLine("-- DONE --");
                Console.ReadLine();
            }
            catch (UnauthorizedAccessException)
            {
                // If the token has expired, prompt the user with a login prompt
                result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, new Uri(replyUri), promptBehavior).Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}: {1}", ex.GetType(), ex.Message);
            }
            finally
            {
            }
        }
Ejemplo n.º 42
0
        public IEnumerable <TeamProjectReference> InteractiveADAL(string vstsAccountName, string applicationId)
        {
            AuthenticationContext authenticationContext = new AadAuthenticationContext("https://login.windows.net/common", validateAuthority: true);
            var authenticationResultTask = authenticationContext.AcquireTokenAsync(VSTSResourceId, applicationId, new Uri(RedirectUri), new PlatformParameters(PromptBehavior.Auto));
            AuthenticationResult authenticationResult = authenticationResultTask.Result;

            VssOAuthAccessTokenCredential oAuthCredential = new VssOAuthAccessTokenCredential(authenticationResult.AccessToken);

            return(ListProjectsViaClientLibrary(vstsAccountName, oAuthCredential));
        }
Ejemplo n.º 43
0
        public async Task IntegratedAuthUsingUpn_MexDoesNotReturnAuthEndpointTestAsync()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());
            await context.Authenticator.UpdateFromTemplateAsync(null).ConfigureAwait(false);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"federated\",\"domain_name\":\"microsoft.com\"," +
                                                "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" +
                                                "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," +
                                                "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" +
                                                ",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://msft.sts.microsoft.com/adfs/services/trust/mex")
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("TestMex.xml"))
                }
            });

            // Mex does not return integrated auth endpoint (.../13/windowstransport)
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler("https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport")
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent("Not found")
                }
            });

            // Call acquire token, endpoint not found
            var result = AssertException.TaskThrows <Exception>(() =>
                                                                context.AcquireTokenAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserCredential(TestConstants.DefaultDisplayableId)));

            // Check exception message
            Assert.AreEqual("Federated service at https://msft.sts.microsoft.com/adfs/services/trust/13/windowstransport returned error: See inner exception for detail.", result.Message);
            Assert.AreEqual("Response status code does not indicate success: 404 (NotFound).", result.InnerException.Message);

            // There should be no cached entries.
            Assert.AreEqual(0, context.TokenCache.Count);

            // All mocks are consumed
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
        }
Ejemplo n.º 44
0
        public static async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var clientId = _configuration["KeyVault:AuthClientId"];
            var clientSecret = _configuration["KeyVault:AuthClientSecret"];

            var clientCredential = new ClientCredential(clientId, clientSecret);
            var context = new AuthenticationContext(authority, null);
            var result = await context.AcquireTokenAsync(resource, clientCredential);

            return result.AccessToken;
        }
        internal async Task<string> KeyVaultClientAuthenticationCallback(string authority, string resource, string scope)
        {
            var authContext = new AuthenticationContext(authority);
            ClientCredential clientCred = new ClientCredential(_clientId, _clientSecret);
            AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

            if (result == null)
                throw new InvalidOperationException("Failed to obtain the JWT token");

            return result.AccessToken;
        }
        /// <summary>
        /// Authenticate using the secret for the specified client from the key store
        /// </summary>
        /// <param name="clientId">The active directory client id for the application.</param>
        /// <param name="audience">The intended audience for authentication</param>
        /// <param name="context">The AD AuthenticationContext to use</param>
        /// <returns></returns>
        public async Task<AuthenticationResult> AuthenticateAsync(string clientId, string audience, AuthenticationContext context)
        {
            var task = new Task<SecureString>(() =>
            {
                return ServicePrincipalKeyStore.GetKey(clientId, _tenantId);
            });
            task.Start();
            var key = await task.ConfigureAwait(false);

            return await context.AcquireTokenAsync(audience, new ClientCredential(clientId, key));
        }
Ejemplo n.º 47
0
        //the method that will be provided to the KeyVaultClient
        public async static Task<string> GetToken(string authority, string resource, string scope)
        {
            var authContext = new AuthenticationContext(authority);
            ClientCredential clientCred = new ClientCredential(WebConfigurationManager.AppSettings["ClientId"],
                        WebConfigurationManager.AppSettings["ClientSecret"]);
            AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

            if (result == null)
                throw new InvalidOperationException("Failed to obtain the JWT token");

            return result.AccessToken;
        }
        /// <summary>
        /// Authentication callback that gets a token using the X509 certificate
        /// </summary>
        /// <param name="authority">Address of the authority</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token</param>
        /// <param name="scope">Scope</param>
        /// <returns></returns>
        public static async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var client_id = CloudConfigurationManager.GetSetting(Constants.KeyVaultAuthClientIdSetting);

            var context = new AuthenticationContext(authority, null);
            
            var assertionCert = new ClientAssertionCertificate(client_id, clientAssertionCertPfx);

            var result = await context.AcquireTokenAsync(resource, assertionCert);

            return result.AccessToken;
        }
Ejemplo n.º 49
0
        public static string GetAccessToken()
        {
            AuthenticationContext authContext = new AuthenticationContext(authority);
            var authResult =
               authContext.AcquireTokenAsync(
                   resourceMicrosoftGraphAPI,
                   clientId,
                   replyUrl,
                   new PlatformParameters(PromptBehavior.Auto));

            return authResult.Result.AccessToken;
        }
        private async static Task doStuffInOffice365()
        {
            //set the authentication context
            //you can do multi-tenant app-only, but you cannot use /common for authority...must get tenant ID
            string authority = "https://login.windows.net/rzna.onmicrosoft.com/";
            AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

            //read the certificate private key from the executing location
            //NOTE: This is a hack...Azure Key Vault is best approach
            var certPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            certPath = certPath.Substring(0, certPath.LastIndexOf('\\')) + "\\O365AppOnly_private.pfx";
            var certfile = System.IO.File.OpenRead(certPath);
            var certificateBytes = new byte[certfile.Length];
            certfile.Read(certificateBytes, 0, (int)certfile.Length);
            var cert = new X509Certificate2(
                certificateBytes,
                PRIVATE_KEY_PASSWORD,
                X509KeyStorageFlags.Exportable |
                X509KeyStorageFlags.MachineKeySet |
                X509KeyStorageFlags.PersistKeySet); //switchest are important to work in webjob
            ClientAssertionCertificate cac = new ClientAssertionCertificate(CLIENT_ID, cert);

            //get the access token to SharePoint using the ClientAssertionCertificate
            Console.WriteLine("Getting app-only access token to SharePoint Online");
            var authenticationResult = await authenticationContext.AcquireTokenAsync("https://rzna.sharepoint.com/", cac);
            var token = authenticationResult.AccessToken;
            Console.WriteLine("App-only access token retreived");

            //perform a post using the app-only access token to add SharePoint list item in Attendee list
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

            //create the item payload for saving into SharePoint
            var itemPayload = new
            {
                __metadata = new { type = "SP.Data.SampleListItem" },
                Title = String.Format("Created at {0} {1} from app-only AAD token", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString())
            };

            //setup the client post
            HttpContent content = new StringContent(JsonConvert.SerializeObject(itemPayload));
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            Console.WriteLine("Posting ListItem to SharePoint Online");
            using (HttpResponseMessage response = await client.PostAsync("https://rzna.sharepoint.com/_api/web/Lists/getbytitle('Sample')/items", content))
            {
                if (!response.IsSuccessStatusCode)
                    Console.WriteLine("ERROR: SharePoint ListItem Creation Failed!");
                else
                    Console.WriteLine("SharePoint ListItem Created!");
            }
        }
        /// <summary>
        /// Authenticate using certificate thumbprint from the datastore 
        /// </summary>
        /// <param name="clientId">The active directory client id for the application.</param>
        /// <param name="audience">The intended audience for authentication</param>
        /// <param name="context">The AD AuthenticationContext to use</param>
        /// <returns></returns>
        public async Task<AuthenticationResult> AuthenticateAsync(string clientId, string audience, AuthenticationContext context)
        {
            var task = new Task<X509Certificate2>(() =>
            {
                return  AzureSession.DataStore.GetCertificate(this._certificateThumbprint);
            });
            task.Start();
            var certificate = await task.ConfigureAwait(false);

            return await context.AcquireTokenAsync(
                audience,
                new ClientAssertionCertificate(clientId, certificate));
        }
Ejemplo n.º 52
0
        internal async Task<string> GetTokenHelperAsync(AuthenticationContext context, string resourceId)
        {
            string accessToken = null;
            AuthenticationResult result = null;

            result = await context.AcquireTokenAsync(resourceId, ClientID, _returnUri);

            accessToken = result.AccessToken;

            _settings.Values["LastAuthority"] = context.Authority;

            return accessToken;
        }
Ejemplo n.º 53
0
        private static async Task<string> GetAuthorizationHeader()
        {
            string username = "";
            string password = "";

            var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", TenantId));

            var userCred = new UserCredential(username, password);

            AuthenticationResult result =
                await context.AcquireTokenAsync("https://management.core.windows.net/", ClientId, userCred);

            return result.CreateAuthorizationHeader().Substring("Bearer ".Length);
        }
Ejemplo n.º 54
0
 private async Task<string> GetAccessToken()
 {
     AuthenticationContext authContext = new AuthenticationContext(authority);
     ClientCredential clientCred = new ClientCredential("844ffb77-5bfd-403e-9285-678e2eddc90c", "IAKt/4uoQFM0UJ1Ocj//WHOg1RzLspACzPAKkkPP0kw=");            
     //UserCredential userCredential = new UserCredential("*****@*****.**", "feb@2016"); //Before RTM
     UserCredential userCredential = new UserCredential("*****@*****.**");
     AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://microsoft.onmicrosoft.com/mcserviceadal",
         clientCred);
     return authResult.AccessToken;
     //AuthenticationContext authContext = new AuthenticationContext(clientCredentials.Authority);
     //ClientCredential clientCred = new ClientCredential(clientCredentials.ClientId, clientCredentials.ClientSecret);
     //AuthenticationResult authResult = await authContext.AcquireTokenAsync(clientCredentials.ClientResource, clientCred);
     //return authResult.AccessToken;
 }
Ejemplo n.º 55
0
        public async Task AuthenticateRequestAsync(HttpRequestMessage request) {
            
            // Use ADAL to obtain access token - ADAL performs tokn caching behind the scenes
            AuthenticationContext authContext = new AuthenticationContext(authority);           
            AuthenticationResult authResult =
               await  authContext.AcquireTokenAsync(
                        resourceMicrosoftGraphAPI, 
                        clientId,
                        replyUrl,
                        new PlatformParameters(PromptBehavior.Auto));

            // insert access token into authorization header for each outbound request
            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Get Token for Application.
        /// </summary>
        /// <returns>Token for application.</returns>
        public static async Task<string> GetTokenForApplicationAsync()
        {
            var authenticationUrl = "https://login.windows.net/" + ConfigurationManager.AppSettings["TenantUpnDomain"];
            AuthenticationContext authenticationContext = new AuthenticationContext(authenticationUrl, false);

            // Config for OAuth client credentials 
            ClientCredential clientCred = new ClientCredential(
                ConfigurationManager.AppSettings["ClientId"],
                ConfigurationManager.AppSettings["ClientSecret"]);

            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl,
                clientCred);
            string token = authenticationResult.AccessToken;
            return token;
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Gets the authentication token.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <returns></returns>
        private static string GetAuthToken(string tenantId)
        {
            AuthenticationContext context = new AuthenticationContext(authority: string.Format("https://login.windows.net/{0}", tenantId));

            var acquireTokenTask = context.AcquireTokenAsync(
                    resource: "https://management.core.windows.net/",
                    clientId: "1950a258-227b-4e31-a9cf-717495945fc2",
                    redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"),
                    parameters: new PlatformParameters(promptBehavior: PromptBehavior.Auto, ownerWindow: null));

            acquireTokenTask.Wait();
            var authResult = acquireTokenTask.Result;

            return authResult.CreateAuthorizationHeader().Substring("Bearer ".Length);
        }
        async Task<string> AcquireToken()
        {
            string authString = $"https://login.microsoftonline.com/{credentials.TenantId}";
            string clientId = credentials.UserClaims
                    .FirstOrDefault(c => c.Type == "aud").Value;
            string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];

            var authenticationContext = new AuthenticationContext(authString, false);
            ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

            AuthenticationResult result = await authenticationContext.AcquireTokenAsync(
                            resource: resourceUrl,
                            clientCredential: clientCred);

            return result.AccessToken;
        }
Ejemplo n.º 59
0
        //Get Aacess token for Keyvault client to use
        private static async Task<string> GetAccessToken(string authority, string resource, string scope)
        {

            var authenticationContext = new AuthenticationContext(authority);
            var credential = GetCredential();
            AuthenticationResult result = await authenticationContext.AcquireTokenAsync(resource, credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;

            return token;
        }
Ejemplo n.º 60
-2
        public void Run()
        {
            // Try to obtain the authorization token
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
            var result = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain authorization token");
            }

            // Read the token and create the appropriate credentials object
            string token = result.AccessToken;
            var credentials = new TokenCredentials(token);

            // Read the template and parameter file contents
            JObject templateFileContents = GetJsonFileContents(pathToTemplateFile);
            JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(credentials);
            resourceManagementClient.SubscriptionId = subscriptionId;

            // Create or check that resource group exists
            EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
        }