Exemple #1
0
        /// <inheritdoc/>
        public AuthenticationResponse Authenticate(AuthenticationParameters parameters, string ipAddress)
        {
            var user = _context.Users.SingleOrDefault(x => x.Login == parameters.Username);

            if (user == null || !user.IsVerified || !BC.Verify(parameters.Password, user.PasswordHash))
            {
                return(null);
            }

            var jwtToken     = GenerateJwtToken(user);
            var refreshToken = GenerateRefreshToken(ipAddress);

            user.RefreshTokens.Add(refreshToken);
            _context.Update(user);
            _context.SaveChanges();

            return(new AuthenticationResponse(user, jwtToken, refreshToken.Token));
        }
        public OAuthMessageHandler(string url, string clientId, string username, string password, HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.

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

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

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

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

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

            authHeader = new AuthenticationHeaderValue("Bearer", authResult.Result.AccessToken);
        }
Exemple #3
0
        private AuthenticationResult GetAccessTokenFromAzureAD(Uri orgUri)
        {
            // Get the settings from host.json
            string appID      = ConfigurationManager.AppSettings["ScantegraAutomationAppID"];
            string secretyKey = ConfigurationManager.AppSettings["ScantegraAutomationAppKey"];

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

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

            AuthenticationContext authenticationContext = new AuthenticationContext(authorityUrl);

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

            return(authenticationResult);
        }
        public void RefreshToken_WhenAuthenticatedUserRequestsForRefresh_ReturnNewRefreshedTokensResponse()
        {
            //Arrange
            var parameters = new AuthenticationParameters {
                Username = "******", Password = "******"
            };
            var ip = "127.0.0.1";

            //Act
            var authResponse          = _jwtAuthenticationManager.Authenticate(parameters, ip);
            var refreshedAuthResponse = _jwtAuthenticationManager.RefreshToken(authResponse.RefreshToken, ip);

            //Assert
            //Assert.NotEqual(refreshedAuthResponse.JwtToken, authResponse.JwtToken);
            Assert.NotEqual(refreshedAuthResponse.RefreshToken, authResponse.RefreshToken);
            Assert.NotNull(refreshedAuthResponse.JwtToken);
            Assert.NotNull(refreshedAuthResponse.RefreshToken);
        }
Exemple #5
0
        public bool Authenticate(AuthenticationParameters networkAuthentication)
        {
            var network   = _networkOperations.Get(networkAuthentication.Id);
            var serviceId = network.ServiceId;

            while (network != null)
            {
                if (network.NetworkKey == networkAuthentication.ApiKey)
                {
                    return(true);
                }

                network = network.ParentNetworkId != null?_networkOperations.Get(network.ParentNetworkId) : null;
            }

            var service = _serviceOperations.Get(serviceId);

            return(service.ApiKey == networkAuthentication.ApiKey);
        }
Exemple #6
0
        /// <summary>
        /// Discover the authentication authority asynchronously.
        /// </summary>
        /// <param name="serviceUrl">The specified endpoint address</param>
        /// <returns>The URL of the authentication authority on the specified endpoint address, or an empty string
        /// if the authority cannot be discovered.</returns>
        public static async Task <string> DiscoverAuthority(string _serviceUrl)
        {
            try
            {
                AuthenticationParameters ap = await AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(_serviceUrl + "/api/aad/challenge"));

                _resource = ap.Resource;
                return(ap.Authority);
            }
            catch (HttpRequestException e)
            {
                throw new Exception("An HTTP request exception occurred during authority discovery.", e);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #7
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_authResult == null)
            {
                var authParams = await AuthenticationParameters.CreateFromResourceUrlAsync(_resourceUri);

                _authContext = new AuthenticationContext(authParams.Authority);
                _authResult  = _authContext.AcquireToken(authParams.Resource, _clientId, _credential);
            }

            if (_authResult.ExpiresOn < DateTimeOffset.UtcNow)
            {
                _authResult = await _authContext.AcquireTokenByRefreshTokenAsync(_authResult.RefreshToken, _clientId);
            }

            request.Headers.Authorization = new AuthenticationHeaderValue(_authResult.AccessTokenType, _authResult.AccessToken);

            return(await base.SendAsync(request, cancellationToken));
        }
Exemple #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press S for clientid/secret, C for certificate auth");
            var key = Console.ReadKey();

            Task.Run(async() =>
            {
                string clientId     = ConfigurationManager.AppSettings["ClientId"];
                string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
                string apiUrl       = ConfigurationManager.AppSettings["ApiUrl"];
                string thumb        = ConfigurationManager.AppSettings["CertThumb"];

                var authParams  = await AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl));
                var authContext = new AuthenticationContext(authParams.Authority);

                // clientid/secret
                var clientCreds = new ClientCredential(clientId, clientSecret);

                // certificate
                X509Store store = new X509Store(StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);
                var certs     = store.Certificates.Find(X509FindType.FindByThumbprint, thumb, false);
                var cert      = certs[0];
                var certCreds = new ClientAssertionCertificate(clientId, certs[0]);

                AuthenticationResult result;
                if (key.Key == ConsoleKey.S)
                {
                    result = await authContext.AcquireTokenAsync(authParams.Resource,
                                                                 clientCreds);
                }
                else
                {
                    result = await authContext.AcquireTokenAsync(authParams.Resource,
                                                                 certCreds);
                }

                CRMWebAPI api  = new CRMWebAPI(apiUrl, result.AccessToken);
                dynamic whoAmI = await api.ExecuteFunction("WhoAmI");
                Console.WriteLine($"{whoAmI.OrganizationId},{whoAmI.BusinessUnitId},{whoAmI.UserId}");
                Console.ReadLine();
            }).Wait();
        }
        private async Task <string> AuthenticationCallbackAsync(
            string authority,
            string resource,
            string scope)
        {
            var msalConfiguration = new MsalClientConfiguration();
            var pca = new PublicClientApplication(msalConfiguration);
            //var authContext = new AuthenticationContext(authority, keyVaultTokenCache);

            var authParameters = new AuthenticationParameters
            {
                Authority = authority,
                ClientId  = _config.ClientId,
            };

            authParameters.AddScopes(ScopeUtils.Split(scope));
            authParameters.AddScope("https://vault.azure.net/.default");

            switch (_config.AuthType)
            {
            case KeyVaultAuthenticationType.ClientCertificate:
                var cert = CertificateHelper.FindCertificateByThumbprint(_config.CertThumbprint);
                authParameters.Certificate       = cert;
                authParameters.AuthorizationType = AuthorizationType.Certificate;

                // authContext.AcquireTokenAsync(resource, _assertionCert));
                break;

            case KeyVaultAuthenticationType.UserCredential:
                authParameters.AuthorizationType = AuthorizationType.WindowsIntegratedAuth;
                //authResult = await authContext.AcquireTokenAsync(resource, _config.ClientId, new UserCredential());
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var authResult = await pca.AcquireTokenSilentlyAsync(authParameters, CancellationToken.None)
                             .ConfigureAwait(false);

            return(authResult?.AccessToken);
        }
Exemple #10
0
    static void Main(string[] args)
    {
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls |
                                                          System.Net.SecurityProtocolType.Tls11 |
                                                          System.Net.SecurityProtocolType.Tls12 |
                                                          System.Net.SecurityProtocolType.Ssl3;
        // parse query parameter
        // string name = req.GetQueryNameValuePairs()
        //     .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        //     .Value;

        // https://login.microsoftonline.com/15017f46-17d2-456e-b42f-4724ab6059b7/oauth2/authorize

        string username             = "******";
        string password             = "******";
        string apiUrl               = "https://aryan123.crm.dynamics.com/api/data/v8.2/";
        string adTenant             = "https://login.windows.net/common";
        string adClientAppId        = "fdab829e-74dd-471d-9c81-431e1e3e0ada";
        AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result;

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

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


        // AuthenticationContext authContext = new AuthenticationContext(adTenant);

        var userCredential = new UserPasswordCredential(username, password);

        AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(apiUrl, adClientAppId, userCredential).Result;


        //  return req.CreateResponse(HttpStatusCode.OK, authenticationResult.CreateAuthorizationHeader());

        //    return name == null
        //         ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        //         : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }
        public HttpResponseMessage ResetPassword(AuthenticationParameters model)
        {
            if (model == null)// Incase Post Object Is Null or Not Match and Object value is null
            {
                result = new ReponseMessage(MsgNo: HttpStatusCode.BadRequest.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: "Object is null");
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }
            if (ModelState.IsValid)
            {
                string Authenticated = AuthenticationServices.ResetPassword(model);

                return(Request.CreateResponse(HttpStatusCode.OK, Authenticated));
            }
            else
            {
                result = new ReponseMessage(MsgNo: HttpStatusCode.BadRequest.ToCode(), MsgType: MsgTypeEnum.E.ToString(), Message: "", Validation: ModelState.AllErrors());
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }
            return(null);
        }
Exemple #12
0
        public AuthenticationResult GetServiceAccessToken()
        {
            string TargetOrgUri = ConfigurationManager.AppSettings["ResourceUri"] + "XRMServices/2011/Organization.svc/web?SdkClientVersion=9.0.0.533";

            if (ctxParms == null)
            {
                ctxParms = GetAuthorityFromTargetService(new Uri(TargetOrgUri));
            }

            string clientId      = ConfigurationManager.AppSettings["ClientId"];
            string appKey        = ConfigurationManager.AppSettings["AppSecret"];
            string cdsResourceId = ctxParms.Resource;

            AuthenticationContext authContext = new AuthenticationContext(ctxParms.Authority);
            ClientCredential      credential  = new ClientCredential(clientId, appKey); // this is the site application ( needed to be granted impersonate CRM user )
            UserIdentifier        currentUser = new UserIdentifier(ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value, UserIdentifierType.UniqueId);
            AuthenticationResult  accessToken = authContext.AcquireTokenSilentAsync(cdsResourceId, credential, currentUser).Result;

            return(accessToken);
        }
Exemple #13
0
 public static int UpdateToken(AuthenticationParameters filter)
 {
     try
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             MySqlCommand cmd = new MySqlCommand("sp_save_token", conn);
             cmd.CommandType = CommandType.StoredProcedure;
             cmd.Parameters.Add("@_user_code", MySqlDbType.String).Value = filter._user_code;
             cmd.Parameters.Add("@_token", MySqlDbType.String).Value     = filter._token;
             conn.Open();
             int result = cmd.ExecuteNonQuery();
             return(result);
         }
     }
     catch (Exception e)
     {
         return(-1);
     }
 }
Exemple #14
0
        private async Task <AuthenticationContext> GetStaff(AuthenticationParameters parameters)
        {
            var staff = await _dbContext.Staff.FirstOrDefaultAsync(e => e.MobileNumber.Equals(parameters.Identifier) &&
                                                                   e.AreaCode.Equals(parameters.AreaCode) &&
                                                                   e.Status == UserStatus.Active);

            if (staff == null)
            {
                return(null);
            }

            return(new AuthenticationContext
            {
                UserId = staff.Id,
                Type = staff.Role == StaffMemberRole.Manager ? UserType.Manager : UserType.Staff,
                RequiredMethods = new List <AuthenticationMethod> {
                    AuthenticationMethod.Biometrics
                }
            });
        }
Exemple #15
0
        public static string GetAccessToken(string userName, string password, Uri serviceRoot)
        {
            var    targetServiceUrl = GetUriBuilderWithVersion(serviceRoot);
            string _resource;
            string _authority;

            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            AuthenticationParameters ap;

            //ap = GetAuthorityFromTargetService(targetServiceUrl.Uri);
            //AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);
            ap         = AuthenticationParameters.CreateFromResponseAuthenticateHeader("Bearer authorization_uri=https://login.microsoftonline.com/common/oauth2/authorize,resource_id=https://globaldisco.crm10.dynamics.com/");
            _authority = ap.Authority;
            _resource  = ap.Resource;

            AuthenticationContext authContext = new AuthenticationContext(_authority, false);

            //AuthenticationContext authContext = new AuthenticationContext(authority, false);
            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            AuthenticationResult authResult;

            if (userName != string.Empty && password != string.Empty)
            {
                UserPasswordCredential cred = new UserPasswordCredential(userName, password);
                authResult = authContext.AcquireTokenAsync(_resource, clientId, cred).Result;
            }
            else
            {
                // new
                var clientCertName             = "serviceauth.local-operations365.dynamics.com";
                var certificate                = CertificateLoader.LoadFromStoreCert(clientCertName, "My", StoreLocation.LocalMachine, allowInvalid: false);
                var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);
                authResult = authContext.AcquireTokenAsync(_resource, clientAssertionCertificate, true).Result;

                // old
                //PlatformParameters platformParameters = new PlatformParameters(PromptBehavior.Auto);
                //authResult = authContext.AcquireTokenAsync(ap.Resource, clientId, new Uri(redirectUrl), platformParameters).Result;
            }

            return(authResult.AccessToken);
        }
        public void AuthenticationParametersTest()
        {
            string       authority = "https://login.windows.net/common/oauth2/authorize";
            const string Resource  = "test_resource";

            AuthenticationParameters authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"Bearer authorization_uri=""{0}"",resource_id=""{1}""", authority, Resource));

            Assert.AreEqual(authority, authParams.Authority);
            Assert.AreEqual(Resource, authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"bearer Authorization_uri=""{0}"",Resource_ID=""{1}""", authority, Resource));
            Assert.AreEqual(authority, authParams.Authority);
            Assert.AreEqual(Resource, authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"Bearer authorization_uri=""{0}""", authority));
            Assert.AreEqual(authority, authParams.Authority);
            Assert.IsNull(authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"Bearer resource_id=""{0}""", Resource));
            Assert.AreEqual(Resource, authParams.Resource);
            Assert.IsNull(authParams.Authority);

            try
            {
                AuthenticationParameters.CreateFromResponseAuthenticateHeader(null);
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual(ex.ParamName, "authenticateHeader");
            }

            try
            {
                AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"authorization_uri=""{0}"",Resource_id=""{1}""", authority, Resource));
            }
            catch (ArgumentException ex)
            {
                Assert.AreEqual(ex.ParamName, "authenticateHeader");
                Assert.IsTrue(ex.Message.Contains("format"));
            }
        }
        public void AuthenticationParametersTest()
        {
            const string Authority = "https://login.windows.net/aadadfs.onmicrosoft.com/oauth2/authorize";
            const string Resource  = "test_resource";

            AuthenticationParameters authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(@"Bearer authorization_uri=""{0}"",resource_id=""{1}""", Authority, Resource));

            Verify.AreEqual(Authority, authParams.Authority);
            Verify.AreEqual(Resource, authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(@"bearer Authorization_uri=""{0}"",Resource_ID=""{1}""", Authority, Resource));
            Verify.AreEqual(Authority, authParams.Authority);
            Verify.AreEqual(Resource, authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(@"Bearer authorization_uri=""{0}""", Authority));
            Verify.AreEqual(Authority, authParams.Authority);
            Verify.IsNull(authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(@"Bearer resource_id=""{0}""", Resource));
            Verify.AreEqual(Resource, authParams.Resource);
            Verify.IsNull(authParams.Authority);

            try
            {
                AuthenticationParameters.CreateFromResponseAuthenticateHeader(null);
            }
            catch (ArgumentNullException ex)
            {
                Verify.AreEqual(ex.ParamName, "authenticateHeader");
            }

            try
            {
                AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(@"authorization_uri=""{0}"",Resource_id=""{1}""", Authority, Resource));
            }
            catch (ArgumentException ex)
            {
                Verify.AreEqual(ex.ParamName, "authenticateHeader");
                Verify.IsTrue(ex.Message.Contains("format"));
            }
        }
        private AuthenticationResult GetAccessTokenFromAzureAD(Uri orgUrl)
        {
            var clientSecret = CryptoManager.Decrypt(_connection.S2SClientSecret, ConnectionManager.CryptoPassPhrase,
                                                     ConnectionManager.CryptoSaltValue,
                                                     ConnectionManager.CryptoHashAlgorythm,
                                                     ConnectionManager.CryptoPasswordIterations,
                                                     ConnectionManager.CryptoInitVector,
                                                     ConnectionManager.CryptoKeySize);

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

            if (!String.IsNullOrEmpty(result.RefreshToken))
            {
                _connection.RefreshToken = result.RefreshToken;
            }

            return(result);
        }
Exemple #19
0
        public static string GetAccessToken(string userName, string password, Uri serviceRoot)
        {
            var targetServiceUrl = GetUriBuilderWithVersion(serviceRoot);
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            AuthenticationParameters ap          = GetAuthorityFromTargetService(targetServiceUrl.Uri);
            AuthenticationContext    authContext = new AuthenticationContext(ap.Authority, false);
            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            AuthenticationResult authResult;

            if (userName != string.Empty && password != string.Empty)
            {
                UserPasswordCredential cred = new UserPasswordCredential(userName, password);
                authResult = authContext.AcquireTokenAsync(ap.Resource, clientId, cred).Result;
            }
            else
            {
                PlatformParameters platformParameters = new PlatformParameters(PromptBehavior.Auto);
                authResult = authContext.AcquireTokenAsync(ap.Resource, clientId, new Uri(redirectUrl), platformParameters).Result;
            }

            return(authResult.AccessToken);
        }
        public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken)
        {
            var deviceCodeParameters = parameters as DeviceCodeParameters;
            var tokenCacheProvider   = parameters.TokenCacheProvider;
            var onPremise            = parameters.Environment.OnPremise;
            //null instead of "organizations" should be passed to Azure.Identity to support MSA account
            var tenantId = onPremise ? AdfsTenant :
                           (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId);
            var resource  = parameters.Environment.GetEndpoint(parameters.ResourceId) ?? parameters.ResourceId;
            var scopes    = AuthenticationHelpers.GetScope(onPremise, resource);
            var clientId  = AuthenticationHelpers.PowerShellClientId;
            var authority = parameters.Environment.ActiveDirectoryAuthority;

            var requestContext = new TokenRequestContext(scopes);

            AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache);

            DeviceCodeCredentialOptions options = new DeviceCodeCredentialOptions()
            {
                DeviceCodeCallback = DeviceCodeFunc,
                AuthorityHost      = new Uri(authority),
                ClientId           = clientId,
                TenantId           = onPremise ? tenantId : null,
                TokenCache         = tokenCache.TokenCache,
            };
            var codeCredential = new DeviceCodeCredential(options);
            var source         = new CancellationTokenSource();

            source.CancelAfter(TimeSpan.FromMinutes(5));

            var authTask = codeCredential.AuthenticateAsync(requestContext, source.Token);

            return(MsalAccessToken.GetAccessTokenAsync(
                       authTask,
                       codeCredential,
                       requestContext,
                       source.Token));
        }
Exemple #21
0
        public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken)
        {
            var upParameters       = parameters as UsernamePasswordParameters;
            var onPremise          = upParameters.Environment.OnPremise;
            var tenantId           = onPremise ? AdfsTenant : upParameters.TenantId; //Is user name + password valid in Adfs env?
            var tokenCacheProvider = upParameters.TokenCacheProvider;
            var resource           = upParameters.Environment.GetEndpoint(upParameters.ResourceId) ?? upParameters.ResourceId;
            var scopes             = AuthenticationHelpers.GetScope(onPremise, resource);
            var clientId           = AuthenticationHelpers.PowerShellClientId;
            var authority          = upParameters.Environment.ActiveDirectoryAuthority;

            var requestContext = new TokenRequestContext(scopes);
            UsernamePasswordCredential passwordCredential;

            AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache);

            var credentialOptions = new UsernamePasswordCredentialOptions()
            {
                AuthorityHost = new Uri(authority),
                TokenCache    = tokenCache.TokenCache
            };

            if (upParameters.Password != null)
            {
                passwordCredential = new UsernamePasswordCredential(upParameters.UserId, upParameters.Password.ConvertToString(), tenantId, clientId, credentialOptions);
                TracingAdapter.Information($"{DateTime.Now:T} - [UsernamePasswordAuthenticator] Calling UsernamePasswordCredential.AuthenticateAsync - TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{authority}', UserId:'{upParameters.UserId}'");
                var authTask = passwordCredential.AuthenticateAsync(requestContext, cancellationToken);
                return(MsalAccessToken.GetAccessTokenAsync(
                           authTask,
                           passwordCredential,
                           requestContext,
                           cancellationToken));
            }
            else
            {
                throw new InvalidOperationException(Resources.MissingPasswordAndNoCache);
            }
        }
Exemple #22
0
        public OAuthMessageHandler(string serviceUrl, string clientId, string redirectUrl, string username, string password,
                                   HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                new Uri(serviceUrl + "/api/data/")).Result;
            AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);
            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            AuthenticationResult authResult;

            if (username != string.Empty && password != string.Empty)
            {
                UserCredential cred = new UserCredential(username, password);
                authResult = authContext.AcquireToken(serviceUrl, clientId, cred);
            }
            else
            {
                authResult = authContext.AcquireToken(serviceUrl, clientId, new Uri(redirectUrl), PromptBehavior.Auto);
            }

            authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }
Exemple #23
0
        private void testConnection()
        {
            string organizationUrl = "https://csp-build.crm.dynamics.com";
            string resourceURL     = "https://csp-build.api.crm.dynamics.com" + "/api/data/";
            string clientId        = "c4e4407b-66d1-4452-9b05-db0a0ce9baef"; // Client Id
            string appKey          = "Sy[?Mk106C2OvHXZ:Krytwj=_XN_KKlh";     //Client Secret

            //Create the Client credentials to pass for authentication
            ClientCredential clientcred = new ClientCredential(clientId, appKey);


            //get the authentication parameters
            AuthenticationParameters authParam = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(resourceURL)).Result;

            //Generate the authentication context - this is the azure login url specific to the tenant
            string authority = authParam.Authority;

            //request token
            AuthenticationResult authenticationResult = new AuthenticationContext(authority).AcquireTokenAsync(organizationUrl, clientcred).Result;

            //get the token
            string token = authenticationResult.AccessToken;

            Uri serviceUrl = new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=9.1");
            OrganizationWebProxyClient sdkService;

            Microsoft.Xrm.Sdk.IOrganizationService _orgService;

            sdkService             = new OrganizationWebProxyClient(serviceUrl, false);
            sdkService.CallerId    = new Guid("{A9D51F0B-B11B-E611-80E0-5065F38AA901}");
            sdkService.HeaderToken = token;

            _orgService = (Microsoft.Xrm.Sdk.IOrganizationService)sdkService != null ? (Microsoft.Xrm.Sdk.IOrganizationService)sdkService : null;


            Microsoft.Xrm.Sdk.Entity user = _orgService.Retrieve("systemuser", new Guid("{A9D51F0B-B11B-E611-80E0-5065F38AA901}"), new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
        }
        public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken)
        {
            var interactiveParameters = parameters as InteractiveParameters;
            var onPremise             = interactiveParameters.Environment.OnPremise;
            //null instead of "organizations" should be passed to Azure.Identity to support MSA account
            var tenantId = onPremise ? AdfsTenant :
                           (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId);
            var tokenCacheProvider = interactiveParameters.TokenCacheProvider;
            var resource           = interactiveParameters.Environment.GetEndpoint(interactiveParameters.ResourceId) ?? interactiveParameters.ResourceId;
            var scopes             = AuthenticationHelpers.GetScope(onPremise, resource);
            var clientId           = AuthenticationHelpers.PowerShellClientId;

            var requestContext = new TokenRequestContext(scopes);
            var authority      = interactiveParameters.Environment.ActiveDirectoryAuthority;

            AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache);

            var options = new InteractiveBrowserCredentialOptions()
            {
                ClientId      = clientId,
                TenantId      = tenantId,
                TokenCache    = tokenCache.TokenCache,
                AuthorityHost = new Uri(authority),
                RedirectUri   = GetReplyUrl(onPremise, interactiveParameters),
            };
            var browserCredential = new InteractiveBrowserCredential(options);

            TracingAdapter.Information($"{DateTime.Now:T} - [InteractiveUserAuthenticator] Calling InteractiveBrowserCredential.AuthenticateAsync with TenantId:'{options.TenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}', RedirectUri:'{options.RedirectUri}'");
            var authTask = browserCredential.AuthenticateAsync(requestContext, cancellationToken);

            return(MsalAccessToken.GetAccessTokenAsync(
                       authTask,
                       browserCredential,
                       requestContext,
                       cancellationToken));
        }
Exemple #25
0
        public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken)
        {
            var msiParameters = parameters as ManagedServiceIdentityParameters;

            var scopes         = new[] { GetResourceId(msiParameters.ResourceId, msiParameters.Environment) };
            var requestContext = new TokenRequestContext(scopes);
            var userAccountId  = SystemMsiNameRegex.IsMatch(msiParameters.Account.Id) ? null : msiParameters.Account.Id;

            AzureSession.Instance.TryGetComponent(nameof(AzureCredentialFactory), out AzureCredentialFactory azureCredentialFactory);
            AzureSession.Instance.TryGetComponent(nameof(MsalAccessTokenAcquirerFactory), out MsalAccessTokenAcquirerFactory msalAccessTokenAcquirerFactory);

            var identityCredential      = azureCredentialFactory.CreateManagedIdentityCredential(userAccountId);
            var msalAccessTokenAcquirer = msalAccessTokenAcquirerFactory.CreateMsalAccessTokenAcquirer();
            var parametersLog           = $"- TenantId:'{msiParameters.TenantId}', Scopes:'{string.Join(",", scopes)}', UserId:'{userAccountId}'";

            return(msalAccessTokenAcquirer.GetAccessTokenAsync(
                       nameof(ManagedServiceIdentityAuthenticator),
                       parametersLog,
                       identityCredential,
                       requestContext,
                       cancellationToken,
                       msiParameters.TenantId,
                       msiParameters.Account.Id));
        }
        public static async Task Auth()
        {
            // use below lines for old version (3.13.5)  of adal library
            //    AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
            //    new Uri(API_URL)).Result;

            //Use below lines for latest version of adal library
            AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync(
           new Uri(API_URL)).Result; //for latest version of adal
            
            // use below lines for old version (3.13.5)  of adal library
            //AuthenticationContext authContext = new AuthenticationContext(ap.Authority);

            //Use below lines for latest version of adal library
            AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/<yourtenantid>");
            var clinetCredential = new ClientCredential(CLIENT_ID, CLIENT_SECRET);
            var token = authContext.AcquireTokenAsync(ap.Resource, clinetCredential).Result.AccessToken;
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = new TimeSpan(0, 2, 0);
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                HttpResponseMessage response = await httpClient.GetAsync(API_URL + "/contacts?$top=1");
            }
        }
        public void AuthenticationParametersTest()
        {
            string       authority = TestConstants.DefaultAuthorityCommonTenant + "/oauth2/authorize";
            const string Resource  = "test_resource";

            AuthenticationParameters authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"Bearer authorization_uri=""{0}"",resource_id=""{1}""", authority, Resource));

            Assert.AreEqual(authority, authParams.Authority);
            Assert.AreEqual(Resource, authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"bearer Authorization_uri=""{0}"",Resource_ID=""{1}""", authority, Resource));
            Assert.AreEqual(authority, authParams.Authority);
            Assert.AreEqual(Resource, authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"Bearer authorization_uri=""{0}""", authority));
            Assert.AreEqual(authority, authParams.Authority);
            Assert.IsNull(authParams.Resource);

            authParams = AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"Bearer resource_id=""{0}""", Resource));
            Assert.AreEqual(Resource, authParams.Resource);
            Assert.IsNull(authParams.Authority);

            // Null parameter -> error
            var ex = AssertException.Throws <ArgumentNullException>(() =>
                                                                    AuthenticationParameters.CreateFromResponseAuthenticateHeader(null));

            Assert.AreEqual(ex.ParamName, "authenticateHeader");


            // Invalid format -> error
            var argEx = AssertException.Throws <ArgumentException>(() =>
                                                                   AuthenticationParameters.CreateFromResponseAuthenticateHeader(string.Format(CultureInfo.InvariantCulture, @"authorization_uri=""{0}"",Resource_id=""{1}""", authority, Resource)));

            Assert.AreEqual(argEx.ParamName, "authenticateHeader");
            Assert.IsTrue(argEx.Message.Contains("format"));
        }
Exemple #28
0
 public override bool CanAuthenticate(AuthenticationParameters parameters)
 {
     return((parameters as AccessTokenParameters) != null);
 }
Exemple #29
0
 public Key(AuthenticationParameters parameterSet, byte[] bytes) : base(parameterSet, bytes)
 {
 }
 public override bool CanAuthenticate(AuthenticationParameters parameters)
 {
     return((parameters as UsernamePasswordParameters) != null);
 }