/// <summary>
        /// Gets the AD token for the requests, for the received customer tenant.
        /// </summary>
        public async Task<AuthorizationToken> GetADTokenForRequests(string customerTenant)
        {
            if (_tokenForRequests != null)
            {
                // already initialized
                return _tokenForRequests;
            }

            AuthenticationContext _authenticationContext = new AuthenticationContext(string.Format(Constants.AAD_INSTANCE,
                customerTenant));

            UserCredential _userCredential = new UserCredential(Constants.CSP_SERVICE_USERNAME,
                Constants.CSP_SERVICE_PASSWORD);

            // else. Initialize and return
            AuthenticationResult authenticationResult = await _authenticationContext.AcquireTokenAsync(
                  Constants.GRAPH_RESOURCE_URL,
                  Constants.AZURE_AD_APP_ID_NATIVE_APP,
                  _userCredential);

            _tokenForRequests = new AuthorizationToken(authenticationResult.AccessToken,
             authenticationResult.ExpiresOn.DateTime);

            return _tokenForRequests;
        }
예제 #2
0
 protected AzureLoginUserBase(string subscriptionId, string clientId, string tenant, string userName, string password)
 {
     SubscriptionId = subscriptionId;
     this.clientId = clientId;
     this.tenant = tenant;
     userCredential = new UserCredential(userName, password);
 }
예제 #3
0
파일: Program.cs 프로젝트: tandis/PnP
        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 string GetAccessTokenUsingServiceAccount(Item azureSetting)
 {
     string tenantId;
     string clientId;
     string url;
     SetAzureAuthAppInformation(azureSetting, out tenantId, out clientId, out url);
     if (string.IsNullOrEmpty(tenantId) ||
         string.IsNullOrEmpty(clientId) ||
         string.IsNullOrEmpty(url))
     {
         return string.Empty;
     }
     var authenticationContext = new AuthenticationContext("https://login.windows.net/" + tenantId);
     //get the service account user name and password from the settings node
     string userName = azureSetting["Service Account User Name"];
     string password = azureSetting["Service Account Password"];
     //Create a user credential object using the specified service account user name and password
     var credential = new UserCredential(userName, password);
     //Issue a request to obtain the access token
     var result = authenticationContext.AcquireToken("https://management.core.windows.net/", clientId, credential);
     if (result == null)
     {
         throw new InvalidOperationException("Failed to obtain the JWT token");
     }
     //Set the access token to be returned
     string token = result.AccessToken;
     return token;
 }
        public static async Task <AuthenticationResult> GetAuthorizationHeader(String Username, SecureString Password, String authority = "common")
        {
            var Creds       = new Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential(Username, Password);
            var AuthContext = new AuthenticationContext(Constants.loginAuthority + authority);

            return(await AuthContext.AcquireTokenAsync(Constants.appIdURI, Constants.clientID, Creds));
        }
예제 #6
0
        public static string GetAuthorizationHeader()
        {
            //
            string _aadTenantDomain = "cciccat.partner.onmschina.cn";
            _aadTenantDomain = ConfigurationSettings.AppSettings["_aadTenantDomain"];
            //_aadTenantDomain = "cciccat.com";
            string _aadClientId = "9adbfe5e-2252-4d26-a3ad-68bbd1e25963";
            _aadClientId = ConfigurationSettings.AppSettings["_aadClientId"];

            AuthenticationResult result = null;
            var context = new AuthenticationContext("https://login.chinacloudapi.cn/" + _aadTenantDomain);

            // Directly specify the username and password. 
            var credential = new UserCredential(
                ConfigurationSettings.AppSettings["CoAdminUser"],
                ConfigurationSettings.AppSettings["CoAdminPassword"]);
            result = context.AcquireToken(
                "https://management.core.chinacloudapi.cn/",
                _aadClientId,
                    credential);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;
            return token;

        }
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var userCredential        = new ActiveDirectory.UserCredential();

                ActiveDirectory.AuthenticationResult result = await AdalExtentions.AcquireTokenAsync(authenticationContext,
                                                                                                     resource,
                                                                                                     clientId,
                                                                                                     userCredential);

                return(new Result(result));
            }
            catch (ActiveDirectory.AdalException exception)
            {
                throw new AuthenticationException(exception);
            }
        }
 /// <summary>
 /// Acquires token via non-interactive flow.
 /// </summary>
 /// <param name="authority">The authority.</param>
 /// <param name="resource">The resource.</param>
 /// <param name="clientId">The client identifier.</param>
 /// <param name="userCredential">The user credential.</param>
 /// <remarks>
 /// We use reflection to call ADAL.NET internals to handle token acquisition, since the library does not support ADFS yet.
 /// </remarks>
 public static AuthenticationResult AcquireTokenForAdfs(string authority, string resource, string clientId, UserCredential userCredential)
 {
     // BUG: 2384273 - [PowerShell]: Remove AuthenticationContextExtensions class and integrate support of non-interactive flow via legitimate APIs of ADAL.NET
     var context = new AuthenticationContext(authority: authority, validateAuthority: false, tokenCache: TokenCache.DefaultShared);
     var parameters = GetNewInstanceOfRequestParameters(resource, clientId, userCredential);
     var handler = GetNewInstanceOfNonInteractiveHandler(context, resource, clientId, userCredential);
     return handler.SendHttpMessage(parameters: parameters);
 }
        public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string[] scope, string clientId, UserCredential userCredential)
            : base(authenticator, tokenCache, scope, new ClientKey(clientId), TokenSubjectType.User)
        {
            if (userCredential == null)
            {
                throw new ArgumentNullException("userCredential");
            }

            this.userCredential = userCredential;
        }
예제 #10
0
        private UserCredential UserCredential; //Stores user credentials

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initiazes variables
        /// </summary>
        /// <param name="objUserCredential">UserCredential</param>
        /// <param name="sClientID">string</param>
        internal PollPush(UserCredential objUserCredential, string sClientID)
        {
            UserCredential = objUserCredential;
                clientID = sClientID;
                if (ConfigurationManager.AppSettings["MAXROWSPULL"] != null)
                {
                    iMaxRowsPull = Convert.ToInt32(ConfigurationManager.AppSettings["MAXROWSPULL"]);
                }
                else
                    iMaxRowsPull = 5000;
        }
        public static async Task<WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(wsTrustAddress.Uri.AbsoluteUri);
            request.ContentType = "application/soap+xml;";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            string soapAction = XmlNamespace.Issue.ToString();
            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            Dictionary<string, string> headers = new Dictionary<string, string> 
            { 
                { "SOAPAction", soapAction }
            };

            WsTrustResponse wstResponse;

            try
            {
                HttpHelper.SetPostRequest(request, new RequestParameters(messageBuilder), callState, headers);
                IHttpWebResponse response = await request.GetResponseSyncOrAsync(callState);
                wstResponse = WsTrustResponse.CreateFromResponse(response.GetResponseStream(), wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                    AdalError.FederatedServiceReturnedError,
                    string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                    null,
                    ex);
            }

            return wstResponse;
        }
예제 #12
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;
 }
예제 #13
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);
        }
        public AcquireTokenNonInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, UserCredential userCredential)
            : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User)
        {
            if (userCredential == null)
            {
                throw new ArgumentNullException("userCredential");
            }

            // We enable ADFS support only when it makes sense to do so
            if (authenticator.AuthorityType == AuthorityType.ADFS)
            {
                this.SupportADFS = true;
            }

            this.userCredential = userCredential;
        }
예제 #15
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;
        }
        public static async Task<WsTrustResponse> SendRequestAsync(Uri url, UserCredential credential, CallState callState)
        {
            IHttpClient request = PlatformPlugin.HttpClientFactory.Create(url.AbsoluteUri, callState);
            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, url.AbsoluteUri, credential);
            request.Headers["SOAPAction"] = XmlNamespace.Issue.ToString();

            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters = new StringRequestParameters(messageBuilder);
                IHttpWebResponse response = await request.GetResponseAsync();
                wstResponse = WsTrustResponse.CreateFromResponse(response.ResponseStream);
            }
            catch (HttpRequestWrapperException ex)
            {
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.WebResponse.ResponseStream);
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                    AdalError.FederatedServiceReturnedError,
                    string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, url, errorMessage),
                    null,
                    ex);
            }

            return wstResponse;
        }
        /// <summary>
        /// Get user credential from Credential Manager
        /// </summary>
        /// <param name="Name">Internet or network address label of entry.</param>
        /// <returns>User credential created from values retrieved from credential manager</returns>
        public static UserCredential GetCredential(string Name)
        {
            UserCredential psCredential = null;
            IntPtr credPtr;

            bool success = CredRead(Name, CRED_TYPE.GENERIC, 0, out credPtr);
            if (success)
            {
                var critCred = new CriticalCredentialHandle(credPtr);
                var cred = critCred.GetCredential();
                var username = cred.UserName;
                var securePassword = new SecureString();
                string credentialBlob = cred.CredentialBlob;
                char[] passwordChars = credentialBlob.ToCharArray();
                foreach (char c in passwordChars)
                {
                    securePassword.AppendChar(c);
                }
                psCredential = new UserCredential(username, securePassword);
            }
            return psCredential;
        }
예제 #18
0
 public string GetAuthorizationHeaderSilent()
 {
     AuthenticationResult result = null;
     var context = new AuthenticationContext("https://login.windows.net/" + TenantId);
     // Directly specify the username and password. 
     var credential = 
         new Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential(
             this.UserName,
             this.Password);
     
     result = context.AcquireToken(
         "https://management.core.windows.net/",
         this.ClientId,
         credential);
     
     if (result == null)
     {
         throw new InvalidOperationException("Failed to obtain the JWT token");
     }
     jToken=result.AccessToken;
     return jToken;
 }
예제 #19
0
        public async Task <IAdalResult> AcquireTokenAsync(
            string authorityHostUrl,
            string resource,
            string clientId)
        {
            if (authorityHostUrl is null)
            {
                throw new ArgumentNullException(nameof(authorityHostUrl));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (clientId is null)
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            try
            {
                var authenticationContext = new ActiveDirectory.AuthenticationContext(authorityHostUrl, _cache);
                var userCredential        = new ActiveDirectory.UserCredential();

                ActiveDirectory.AuthenticationResult result = await AdalExtentions.AcquireTokenAsync(authenticationContext,
                                                                                                     resource,
                                                                                                     clientId,
                                                                                                     userCredential);

                return(new Result(result));
            }
            // We should just be able to catch AdalException here but due to an ADAL bug an HttpRequestException can be leaked:
            // https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/1285
            // Until we update to ADAL 4.x or MSAL, we should just workaround this problem.
            catch (Exception exception)
            {
                throw new AuthenticationException(exception);
            }
        }
 public async Task WsTrustRequestXmlFormatTest()
 {
     UserCredential cred = new UserCredential("user", "pass&<>\"'");
     StringBuilder sb = WsTrustRequest.BuildMessage("https://appliesto", new WsTrustAddress { Uri = new Uri("resource") }, cred);
     try
     {
         XmlDocument doc = new XmlDocument();
         doc.LoadXml("<?xml version=\"1.0\"?>" + sb.ToString());
     }
     catch (Exception ex)
     {
         Verify.Fail("Not expected");
     }
 }
        private string AccessToken()
        {
            bool fireAgain = false;
            connectionManager.Properties["PowerBIDataSets"].SetValue(connectionManager, PowerBIDataSetsTxt.Text);
            connectionManager.Properties["ClientID"].SetValue(connectionManager, ClientIdTxt.Text);
            connectionManager.Properties["RedirectUri"].SetValue(connectionManager, RedirectUriTxt.Text);
            connectionManager.Properties["ResourceUri"].SetValue(connectionManager, ResourceUriTxt.Text);
            connectionManager.Properties["OAuth2AuthorityUri"].SetValue(connectionManager, OAuthTxt.Text);
            connectionManager.Properties["PowerBIDataSets"].SetValue(connectionManager, PowerBIDataSetsTxt.Text);
            connectionManager.Properties["UserName"].SetValue(connectionManager, UserNameTxt.Text);
            connectionManager.Properties["Password"].SetValue(connectionManager, PasswordTxt.Text);


            try
            {
                if (token == String.Empty)
                {
                    // Create an instance of TokenCache to cache the access token
                    TokenCache TC = new TokenCache();
                    // Create an instance of AuthenticationContext to acquire an Azure access token
                    authContext = new AuthenticationContext(OAuthTxt.Text, TC);
                    // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                    //token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken.ToString();

                    UserCredential user = new UserCredential(UserNameTxt.Text, PasswordTxt.Text);
                    token = authContext.AcquireToken(ResourceUriTxt.Text, ClientIdTxt.Text, user).AccessToken.ToString();
                }
                else
                {
                    // Get the token in the cache
                    token = authContext.AcquireTokenSilent(ResourceUriTxt.Text, ClientIdTxt.Text).AccessToken;

                }

                return token;
            }
            catch (Exception e)
            {
                return null;
            }

        }
        private async Task <AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserCredential userCredential, bool callSync = false)
        {
            var handler = new AcquireTokenNonInteractiveHandler(this.Authenticator, this.TokenCache, resource, clientId, userCredential, callSync);

            return(await handler.RunAsync());
        }
        /// <summary>
        /// Gets the new instance of non interactive handler.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="userCredential">The user credential.</param>
        private static object GetNewInstanceOfNonInteractiveHandler(AuthenticationContext context, string resource, string clientId, UserCredential userCredential)
        {
            var uriString = EndpointTemplateUri.BindByName(new Uri(context.Authority), TokenEndpointBindings).OriginalString;
            var cache = context.TokenCache;
            var callAsync = false;

            // Retrieve and configure authenticator
            var authenticator = context.Authenticator();
            authenticator.TokenUri(uriString);

            var typeOfObject = Type.GetType("Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenNonInteractiveHandler, Microsoft.IdentityModel.Clients.ActiveDirectory");
            var ctorArguments = new object[] { authenticator, cache, resource, clientId, userCredential, callAsync };
            var instanceOfHandler = Activator.CreateInstance(type: typeOfObject, args: ctorArguments);
            return instanceOfHandler;
        }
        /// <summary>
        /// Gets the new instance of request parameters.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="userCredential">The user credential.</param>
        private static object GetNewInstanceOfRequestParameters(string resource, string clientId, UserCredential userCredential)
        {
            var builder = new StringBuilder();
            var typeOfParameters = Type.GetType("Microsoft.IdentityModel.Clients.ActiveDirectory.RequestParameters, Microsoft.IdentityModel.Clients.ActiveDirectory");
            var arguments = new object[] { builder };
            var instanceOfParameters = (Dictionary<string, string>)Activator.CreateInstance(type: typeOfParameters, args: arguments);

            // Prepare request parameters to be sent over the wire
            instanceOfParameters.Add("grant_type", "password");
            instanceOfParameters.Add("resource", resource);
            instanceOfParameters.Add("username", userCredential.UserName);
            instanceOfParameters.AddSecureParameter("password", userCredential.SecurePassword());
            instanceOfParameters.Add("client_id", clientId);

            return instanceOfParameters;
        }
        public static StringBuilder BuildMessage(string appliesTo, WsTrustAddress wsTrustAddress,
            UserCredential credential)
        {
            // securityHeader will be empty string for Kerberos.
            StringBuilder securityHeaderBuilder = BuildSecurityHeader(wsTrustAddress, credential);

            string guid = Guid.NewGuid().ToString();
            StringBuilder messageBuilder = new StringBuilder(MaxExpectedMessageSize);
            String schemaLocation = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
            String soapAction = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
            String rstTrustNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
            String keyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
            String requestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
                rstTrustNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
                keyType = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey";
                requestType = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
            }

            messageBuilder.AppendFormat(WsTrustEnvelopeTemplate, 
                schemaLocation, soapAction,
                                guid, wsTrustAddress.Uri, securityHeaderBuilder,
                                rstTrustNamespace, appliesTo, keyType,
                                requestType);
            securityHeaderBuilder.SecureClear();

            return messageBuilder;
        }
예제 #26
0
        /// <summary>
        /// Gets the security token with non interactive flow.
        /// </summary>
        private AuthenticationResult GetSecurityTokenWithNonInteractiveFlow()
        {
            var uriString = this.BuildAuthorityUriString();
            var userCredential = new UserCredential(this.Credential.UserName, this.Credential.Password);
            var result = default(AuthenticationResult);

            if (this.IsRequestForAadToken())
            {
                var context = new AuthenticationContext(authority: uriString, validateAuthority: ValidateAuthority);
                result = context.AcquireToken(resource: this.Resource, clientId: this.ClientId, userCredential: userCredential);
            }
            else
            {
                // NOTE: This is a case of using non-public APIs of ADAL.NET via reflection to acquire token (not officially supported by ADAL.NET team).
                result = AuthenticationContextExtensions.AcquireTokenForAdfs(authority: uriString, resource: this.Resource, clientId: this.ClientId, userCredential: userCredential);
            }
            return result;
        }
예제 #27
0
 /// <summary>
 /// Returns the authentication result for the configured authentication context.
 /// </summary>
 /// <returns>The refreshed access token.</returns>
 /// <remarks>Refresh the access token before every service call to avoid having to manage token expiration.</remarks>
 public AuthenticationResult AcquireToken()
 {
     if (_config != null && (!string.IsNullOrEmpty(_config.Username) && _config.Password != null))
     {
         UserCredential cred = new UserCredential(_config.Username, _config.Password);
         return _context.AcquireToken(_service, _clientId, cred);
     }
     return _context.AcquireToken(_service, _clientId, new Uri(_redirectUrl));
 }
        private AuthenticationResult DoAcquireToken(AdalConfiguration config, ShowDialog showDialog, string userId, SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            if (string.IsNullOrEmpty(userId))
            {
                PromptBehavior promptBehavior = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), showDialog.ToString());

                if (promptBehavior != PromptBehavior.Never)
                {
                    ClearCookies();
                }

                result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                        config.ClientRedirectUri, promptBehavior,
                        UserIdentifier.AnyUser, AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                PromptBehavior promptBehavior = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), showDialog.ToString());

                if (password == null)
                {
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                        config.ClientRedirectUri, promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.OptionalDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return result;
        }
        /// <summary>
        /// Acquires security token from the authority.
        /// </summary>
        /// <remarks>This feature is supported only for Azure Active Directory and Active Directory Federation Services (ADFS) on Windows 10.</remarks>
        /// <param name="ctx">Authentication context instance</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="userCredential">The user credential to use for token acquisition.</param>
        /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time.</returns>
        public static async Task <AuthenticationResult> AcquireTokenAsync(this AuthenticationContext ctx, string resource, string clientId, UserCredential userCredential)
        {
            HttpMessageHandlerFactory.UpdateWebProxyNeeded += (sender, args) =>
            {
                args.HttpClient.Proxy = new WebProxy(args.ProxyUrl, true)
                {
                    UseDefaultCredentials = true
                };
            };

            return(await ctx.AcquireTokenCommonAsync(resource, clientId, userCredential).ConfigureAwait(false));
        }
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState, string cloudAudience)
        {
            IHttpClient request = PlatformPlugin.HttpClientFactory.Create(wsTrustAddress.Uri.AbsoluteUri, callState);

            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            if (string.IsNullOrEmpty(cloudAudience))
            {
                cloudAudience = defaultAppliesTo;
            }

            StringBuilder messageBuilder = BuildMessage(cloudAudience, wsTrustAddress, credential);
            string        soapAction     = XmlNamespace.Issue.ToString();

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters        = new StringRequestParameters(messageBuilder);
                request.Headers["SOAPAction"] = soapAction;
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);

                wstResponse = WsTrustResponse.CreateFromResponse(EncodingHelper.GenerateStreamFromString(response.ResponseString), wsTrustAddress.Version);
            }
            catch (HttpRequestWrapperException ex)
            {
                string errorMessage;

                try
                {
                    using (Stream stream = EncodingHelper.GenerateStreamFromString(ex.WebResponse.ResponseString))
                    {
                        XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(stream);
                        errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                    }
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(CultureInfo.CurrentCulture, AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
예제 #31
0
        private IEnumerable<TfsClientCredentials> GetOAuthCredentials()
        {
            try
            {
                var usernameAndPassword = GetServiceIdentityUsernameAndPasswordFromConfig();

                if (usernameAndPassword == null || 
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthClientId) ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthContext) ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthResourceId))
                {
                    return new List<TfsClientCredentials>();
                }

                var userCredential = new UserCredential(usernameAndPassword.Item1, usernameAndPassword.Item2);
                var authContext = new AuthenticationContext(_config.TfsServerConfig.OAuthContext);
                var result = authContext.AcquireToken(_config.TfsServerConfig.OAuthResourceId, _config.TfsServerConfig.OAuthClientId, userCredential);
                var oauthToken = new OAuthTokenCredential(result.AccessToken);
                return new List<TfsClientCredentials>()
                {
                    new TfsClientCredentials(oauthToken)
                };
            }
            catch (Exception ex)
            {
                Logger.WarnFormat("Error trying to generate OAuth Token for TFS connection\n{0}", ex);
                return new List<TfsClientCredentials>();
            }
        }
        public static async Task TokenCacheKeyTestAsync()
        {
            CheckPublicGetSets();

            string authority = "https://www.gotJwt.com/";
            string clientId = Guid.NewGuid().ToString();
            string resource = Guid.NewGuid().ToString();
            string tenantId = Guid.NewGuid().ToString();
            string uniqueId = Guid.NewGuid().ToString();
            string displayableId = Guid.NewGuid().ToString();
            Uri redirectUri = new Uri("https://www.GetJwt.com");

            var authenticationResult = CreateCacheValue(uniqueId, displayableId);
            authority = authority + tenantId + "/";
            UserCredential credential = new UserCredential(displayableId);
            AuthenticationContext tempContext = new AuthenticationContext(authority, false);
            var localCache = tempContext.TokenCache;
            localCache.Clear();

            // @Resource, Credential
            TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId);
            AddToDictionary(localCache, tokenCacheKey, authenticationResult);
            AuthenticationContext acWithLocalCache = new AuthenticationContext(authority, false, localCache);
            AuthenticationResult authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, credential);
            AreAuthenticationResultsEqual(authenticationResult, authenticationResultFromCache);

            // Duplicate throws error
            authenticationResult.UserInfo.UniqueId = null;
            AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, null, displayableId), authenticationResult);

            try
            {
                var result = await acWithLocalCache.AcquireTokenAsync(resource, clientId, credential);
#if TEST_ADAL_WINRT_UNIT
    // ADAL WinRT does not throw exception. It returns error.
                Verify.AreEqual("multiple_matching_tokens_detected", result.Error);
#else
                Verify.Fail("Exception expected");
#endif
            }
            catch (AdalException adae)
            {
                Verify.IsTrue(adae.ErrorCode == "multiple_matching_tokens_detected" && adae.Message.Contains("The cache contains multiple tokens satisfying the requirements"));
            }

            try
            {
                AuthenticationContext acWithDefaultCache = new AuthenticationContext(authority, false);
                var result = await acWithDefaultCache.AcquireTokenAsync(resource, clientId, credential);
#if TEST_ADAL_WINRT_UNIT
                Verify.AreEqual("multiple_matching_tokens_detected", result.Error);
#else
                Verify.Fail("Exception expected");
#endif
            }
            catch (AdalException adae)
            {
                Verify.IsTrue(adae.ErrorCode == "multiple_matching_tokens_detected" && adae.Message.Contains("The cache contains multiple tokens satisfying the requirements"));
            }

            // @resource && @clientId
            acWithLocalCache = new AuthenticationContext(authority, false, localCache);
            localCache.Clear();
            var cacheValue = CreateCacheValue(uniqueId, displayableId);
            resource = Guid.NewGuid().ToString();
            clientId = Guid.NewGuid().ToString();

            TokenCacheKey tempKey = new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, null, null);
            AddToDictionary(localCache, tempKey, cacheValue);
            RemoveFromDictionary(localCache, tempKey);
            Verify.IsFalse(localCache.tokenCacheDictionary.ContainsKey(tempKey));
            AddToDictionary(localCache, tempKey, cacheValue);

#if TEST_ADAL_WINRT_UNIT
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri);
#else
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId);
#endif
            VerifyAuthenticationResultsAreEqual(cacheValue, authenticationResultFromCache);

            // @resource && @clientId && userId
            acWithLocalCache = new AuthenticationContext(authority, false, localCache);
            localCache.Clear();
            resource = Guid.NewGuid().ToString();
            clientId = Guid.NewGuid().ToString();
            uniqueId = Guid.NewGuid().ToString();
            displayableId = Guid.NewGuid().ToString();
            cacheValue = CreateCacheValue(uniqueId, displayableId);
            AddToDictionary(localCache, new TokenCacheKey(authority, resource, clientId, TokenSubjectType.User, uniqueId, displayableId), cacheValue);

            var userId = new UserIdentifier(uniqueId, UserIdentifierType.UniqueId);
            var userIdUpper = new UserIdentifier(displayableId.ToUpper(), UserIdentifierType.RequiredDisplayableId);

#if TEST_ADAL_WINRT_UNIT
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri, PromptBehavior.Auto, userId);
#else
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userId);
#endif
            VerifyAuthenticationResultsAreEqual(cacheValue, authenticationResultFromCache);

#if TEST_ADAL_WINRT_UNIT
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri, PromptBehavior.Auto, userIdUpper);
#else
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId, userIdUpper);
#endif
            VerifyAuthenticationResultsAreEqual(cacheValue, authenticationResultFromCache);

#if TEST_ADAL_WINRT_UNIT
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenAsync(resource, clientId, redirectUri);
#else
            authenticationResultFromCache = await acWithLocalCache.AcquireTokenSilentAsync(resource, clientId);
#endif
            VerifyAuthenticationResultsAreEqual(cacheValue, authenticationResultFromCache);

        }
 private async Task<AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, UserCredential userCredential, bool callSync = false)
 {
     var handler = new AcquireTokenNonInteractiveHandler(this.Authenticator, this.TokenCache, resource, clientId, userCredential, callSync);
     return await handler.RunAsync();
 }
예제 #34
0
 /// <summary>
 /// Returns the authentication result for the configured authentication context.
 /// </summary>
 /// <param name="username">The username of a CRM system user in the target organization. </param>
 /// <param name="password">The password of a CRM system user in the target organization.</param>
 /// <returns>The authentication result.</returns>
 /// <remarks>Setting the username or password parameters to null results in the user being prompted to
 /// enter logon credentails. Refresh the access token before every service call to avoid having to manage
 /// token expiration.</remarks>
 public AuthenticationResult AcquireToken(string username, SecureString password)
 {
     try
     {
         if (!string.IsNullOrEmpty(username) && password != null)
         {
             UserCredential cred = new UserCredential(username, password);
             return _context.AcquireToken(_service, _clientId, cred);
         }
     }
     catch (Exception e)
     {
         throw new Exception("Authentication failed. Verify the configuration values are correct.", e);
     }
     return null;
 }
        private static StringBuilder BuildSecurityHeader(WsTrustAddress address, UserCredential credential)
        {
            StringBuilder securityHeaderBuilder = new StringBuilder(MaxExpectedMessageSize);

            // Not add <Security> element if the credential type is kerberos
            if (credential.UserAuthType == UserAuthType.UsernamePassword)
            {
                StringBuilder messageCredentialsBuilder = new StringBuilder(MaxExpectedMessageSize);
                string guid = Guid.NewGuid().ToString();
                    messageCredentialsBuilder.AppendFormat(
                        "<o:UsernameToken u:Id='uuid-{0}'><o:Username>{1}</o:Username><o:Password>", guid,
                        credential.UserName);
                char[] passwordChars = null;
                try
                {
                    passwordChars = credential.PasswordToCharArray();
                    string escapeStr = XmlEscape(new string(passwordChars));
                    messageCredentialsBuilder.Append(escapeStr);
                    escapeStr = "";
                }
                finally
                {
                    passwordChars.SecureClear();
                }

                    messageCredentialsBuilder.AppendFormat("</o:Password></o:UsernameToken>");
                
                //
                // Timestamp the message
                //
                DateTime currentTime = DateTime.UtcNow;
                string currentTimeString = DateTimeHelper.BuildTimeString(currentTime);

                // Expiry is 10 minutes after creation
                DateTime expiryTime = currentTime.AddMinutes(10);    
                string expiryTimeString = DateTimeHelper.BuildTimeString(expiryTime);

                    securityHeaderBuilder.AppendFormat(
                        "<o:Security s:mustUnderstand='1' xmlns:o='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'><u:Timestamp u:Id='_0'><u:Created>{0}</u:Created><u:Expires>{1}</u:Expires></u:Timestamp>{2}</o:Security>",
                        currentTimeString,
                        expiryTimeString,
                        messageCredentialsBuilder);

                messageCredentialsBuilder.SecureClear();
            }

            return securityHeaderBuilder;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="serviceResourceId"></param>
 /// <param name="activity"></param>
 /// <returns></returns>
 public async void GetAccessToken(string serviceResourceId, Activity activity)
 {
     try
     {
         Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context =
                new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AadAuthority);
         if (context.TokenCache.ReadItems().Count() > 0)
             context = new AuthenticationContext(context.TokenCache.ReadItems().First().Authority);
         username = FindViewById<EditText>(Resource.Id.usernameET).Text;
         password = FindViewById<EditText>(Resource.Id.passwordET).Text; ;
         UserCredential us = new UserCredential(username, password);
         await context.AcquireTokenAsync(serviceResourceId, AadClientID, us).ContinueWith((r) =>
             {
                 OnSuccess(r);
             }
         );
     }
     catch (AggregateException ex)
     {
         ExceptionHandler.HandleException(ex, this);
     }
     catch (Exception ex)
     {
         ExceptionHandler.HandleException(ex, this);
     }
 }
예제 #37
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            IHttpClient request = PlatformPlugin.HttpClientFactory.Create(wsTrustAddress.Uri.AbsoluteUri, callState);

            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            string        soapAction     = XmlNamespace.Issue.ToString();

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters        = new StringRequestParameters(messageBuilder);
                request.Headers["SOAPAction"] = soapAction;
                IHttpWebResponse response = await request.GetResponseAsync();

                wstResponse = WsTrustResponse.CreateFromResponse(response.ResponseStream, wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }