public void HashCode()
        {
            HashSet <int> hashCodes = new HashSet <int>();

            foreach (var item in TokenScope.EnumerateValues())
            {
                Assert.True(hashCodes.Add(item.GetHashCode()));
            }

            int loop1 = 0;

            foreach (var item1 in TokenScope.EnumerateValues())
            {
                int loop2 = 0;

                foreach (var item2 in TokenScope.EnumerateValues())
                {
                    if (loop1 < loop2)
                    {
                        Assert.True(hashCodes.Add((item1 | item2).GetHashCode()));
                    }
                    else
                    {
                        Assert.False(hashCodes.Add((item1 | item2).GetHashCode()));
                    }

                    loop2++;
                }

                loop1++;
            }
        }
        public ServiceBusOptionSet()
        {
            Add<string>("ns=", "The service bus namespace",
                x => ServiceUri = ServiceBusEnvironment.CreateServiceUri("sb", x, "Benchmark"));
            Add<string>("keyname=", "The access key name", x => _keyName = x);
            Add<string>("key=", "The access key", x => _accessKey = x);
            Add<int>("connections=", "The number of connections to configure for the service point manager",
                x => DefaultConnections = x);

            _tokenTimeToLive = TimeSpan.FromDays(1);
            _tokenScope = TokenScope.Namespace;

            OperationTimeout = TimeSpan.FromSeconds(60.0);
            RetryMinBackoff = TimeSpan.FromMilliseconds(100.0);
            RetryMaxBackoff = TimeSpan.FromSeconds(20.0);
            RetryLimit = 10;
            TransportType = Microsoft.ServiceBus.Messaging.TransportType.Amqp;
            AmqpTransportSettings = new AmqpTransportSettings
            {
                BatchFlushInterval = TimeSpan.FromMilliseconds(3.0)
            };
            NetMessagingTransportSettings = new NetMessagingTransportSettings
            {
                BatchFlushInterval = TimeSpan.FromMilliseconds(3.0)
            };

            DefaultConnections = ServicePointManager.DefaultConnectionLimit;
        }
Exemple #3
0
        public async Task <AuthenticationResult> GetAuthAsync(TargetUri targetUri, TokenScope scope, int requestTimeout, Uri restRootUrl, string username, string password)
        {
            // use the provided username and password and attempt a Basic Auth request to a known
            // REST API resource.

            string basicAuthValue = string.Format("{0}:{1}", username, password);

            byte[] authBytes = Encoding.UTF8.GetBytes(basicAuthValue);
            basicAuthValue = Convert.ToBase64String(authBytes);
            var authHeader = "Basic " + basicAuthValue;

            var result = await RestClient.TryGetUser(targetUri, requestTimeout, restRootUrl, authHeader);

            if (result.Type.Equals(AuthenticationResultType.Success))
            {
                // Success with username/passord indicates 2FA is not on so
                // the 'token' is actually the password if we had a
                // successful call then the password is good.
                var token = new Token(password, TokenType.Personal);
                if (!string.IsNullOrWhiteSpace(result.RemoteUsername) && !username.Equals(result.RemoteUsername))
                {
                    Trace.WriteLine($"Remote username [{result.RemoteUsername}] != [{username}] supplied username");
                    return(new AuthenticationResult(AuthenticationResultType.Success, token, result.RemoteUsername));
                }

                return(new AuthenticationResult(AuthenticationResultType.Success, token));
            }

            Trace.WriteLine("authentication failed");
            return(result);
        }
Exemple #4
0
        /// <summary></summary>
        /// <param name="keyName"></param>
        /// <param name="sharedAccessKey"></param>
        /// <param name="customKeyEncoder"></param>
        /// <param name="tokenTimeToLive"></param>
        /// <param name="tokenScope"></param>
        protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, Func <string, byte[]> customKeyEncoder, TimeSpan tokenTimeToLive, TokenScope tokenScope)
        {
            Guard.ArgumentNotNullOrWhiteSpace(nameof(keyName), keyName);

            if (keyName.Length > SharedAccessSignatureToken.MaxKeyNameLength)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(keyName),
                          Resources.ArgumentStringTooBig.FormatForUser(nameof(keyName), SharedAccessSignatureToken.MaxKeyNameLength));
            }

            Guard.ArgumentNotNullOrWhiteSpace(nameof(sharedAccessKey), sharedAccessKey);

            if (sharedAccessKey.Length > SharedAccessSignatureToken.MaxKeyLength)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(sharedAccessKey),
                          Resources.ArgumentStringTooBig.FormatForUser(nameof(sharedAccessKey), SharedAccessSignatureToken.MaxKeyLength));
            }

            this.keyName                = keyName;
            this.tokenTimeToLive        = tokenTimeToLive;
            this.encodedSharedAccessKey = customKeyEncoder != null?
                                          customKeyEncoder(sharedAccessKey) :
                                              MessagingTokenProviderKeyEncoder(sharedAccessKey);

            this.tokenScope = tokenScope;
        }
Exemple #5
0
 public static void Validate(TokenScope value)
 {
     if (!TokenScopeHelper.IsDefined(value))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(TokenScope)));
     }
 }
        public ServiceBusOptionSet()
        {
            Add <string>("ns=", "The service bus namespace",
                         x => ServiceUri = new UriBuilder
            {
                Scheme = "sb",
                Host   = $"{x}.servicebus.windows.net",
                Path   = "Benchmark"
            }.Uri);
            Add <string>("keyname=", "The access key name", x => _keyName = x);
            Add <string>("key=", "The access key", x => _accessKey        = x);
            Add <int>("connections=", "The number of connections to configure for the service point manager", x => DefaultConnections = x);
            Add <bool>("split:", "Split into two bus instances to leverage separate connections", x => Split = x);


            _tokenTimeToLive = TimeSpan.FromDays(1);
            _tokenScope      = TokenScope.Namespace;
            TransportType    = TransportType.Amqp;
            OperationTimeout = TimeSpan.FromSeconds(60.0);
            RetryMinBackoff  = TimeSpan.FromMilliseconds(100.0);
            RetryMaxBackoff  = TimeSpan.FromSeconds(20.0);
            RetryLimit       = 10;

            DefaultConnections = ServicePointManager.DefaultConnectionLimit;
        }
Exemple #7
0
 public GetResolutionWindow(User User, TokenScope Scope)
 {
     this.User  = User;
     this.Scope = Scope;
     InitializeComponent();
     VerifySecretKeyCommand = new DelegateCommand(VerifySecretKey);
 }
Exemple #8
0
 public static bool IsDefined(TokenScope v)
 {
     if (v == TokenScope.Entity)
     {
         return(true);
     }
     return(v == TokenScope.Namespace);
 }
Exemple #9
0
        private Uri GetAuthorizationUri(TokenScope scope)
        {
            const string AuthorizationUrl = "{0}?response_type=code&client_id={1}&state=authenticated&scope={2}&redirect_uri={3}";

            var authorityUrl = string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                             AuthorizationUrl,
                                             AuthorizeUrlPath,
                                             ConsumerKey,
                                             scope.ToString(),
                                             CallbackUri);

            return(new Uri(new Uri("https://bitbucket.org"), authorityUrl));
        }
Exemple #10
0
        public static void Main(string[] args)
        {
            string queueName        = ConfigurationManager.AppSettings["QueueName"];
            string serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"];

            string policyName = ConfigurationManager.AppSettings["SAS_PolicyName"];
            string key        = ConfigurationManager.AppSettings["SAS_Key"];


            // Continuously process messages sent to the "TestQueue"
            while (true)
            {
                Uri        uri        = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Empty);
                TimeSpan   timeSpan   = new TimeSpan(480, 30, 30);
                TokenScope tokenScope = TokenScope.Namespace;

                TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                    policyName,
                    key,
                    timeSpan,
                    tokenScope
                    );
                var             messagingFactory = MessagingFactory.Create(uri, tokenProvider);
                QueueClient     qClient          = messagingFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock);
                BrokeredMessage message          = qClient.Receive();

                if (message != null)
                {
                    try
                    {
                        QueueMessage msg = message.GetBody <QueueMessage>();
                        Console.WriteLine(
                            $"Received {msg.Value} from {msg.ByPerson} queued at {msg.QueuedTime}"
                            );
                        //Console.WriteLine("MessageID: " + message.MessageId);
                        // Remove message from queue
                        message.Complete();

                        Console.WriteLine();

                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception e)
                    {
                        // Indicate a problem, unlock message in queue
                        message.Abandon();
                    }
                }
            }
        }
        /// <summary>
        /// Run the OAuth dance to get a new request_token
        /// </summary>
        /// <param name="targetUri"></param>
        /// <param name="scope"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task <string> Authorize(TargetUri targetUri, TokenScope scope, CancellationToken cancellationToken)
        {
            string url = GetAuthorizationUrl(scope);

            //Open the browser to prompt the user to authorize the token request
            Process.Start(url);

            string rawUrlData;

            try
            {
                //Start a temporary server to handle the callback request and await for the reply
                rawUrlData = await SimpleServer.WaitForURLAsync(CallbackUri, cancellationToken);
            }
            catch (Exception ex)
            {
                string message;
                if (ex.InnerException != null && ex.InnerException.GetType().IsAssignableFrom(typeof(TimeoutException)))
                {
                    message = "Timeout awaiting response from Host service.";
                }
                else
                {
                    message = "Unable to receive callback from OAuth service provider";
                }

                throw new Exception(message, ex);
            }

            //Parse the callback url
            Dictionary <string, string> qs = GetQueryParameters(rawUrlData);

            // look for a request_token code in the parameters
            string authCode = GetAuthenticationCode(qs);

            if (string.IsNullOrWhiteSpace(authCode))
            {
                var error_desc = GetErrorDescription(qs);
                throw new Exception("Request for an OAuth request_token was denied" + error_desc);
            }

            return(authCode);
        }
Exemple #12
0
        private static void SendMessage()
        {
            string queueName        = ConfigurationManager.AppSettings["QueueName"];
            string serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"];

            string policyName = ConfigurationManager.AppSettings["SAS_PolicyName"];
            string key        = ConfigurationManager.AppSettings["SAS_Key"];

            try
            {
                Uri        uri        = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Empty);
                TimeSpan   timeSpan   = new TimeSpan(480, 30, 30);
                TokenScope tokenScope = TokenScope.Namespace;

                TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                    policyName,
                    key,
                    timeSpan,
                    tokenScope
                    );
                //NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider);
                var         messagingFactory = MessagingFactory.Create(uri, tokenProvider);
                QueueClient qClient          = messagingFactory.CreateQueueClient(queueName);


                for (int i = 0; i < 5; i++)
                {
                    var msg = GetMessage();
                    Console.WriteLine(
                        $"Queued {msg.Value} at {msg.QueuedTime} by {msg.ByPerson}"
                        );
                    var brMsg = new BrokeredMessage(msg);
                    qClient.Send(brMsg);
                    System.Threading.Thread.Sleep(2500);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #13
0
        private static Uri CreateQueue()
        {
            string queueName = ConfigurationManager.AppSettings["QueueName"];

            try
            {
                Uri        uri        = ServiceBusEnvironment.CreateServiceUri("sb", "finomial", string.Empty);
                string     name       = "RootManageSharedAccessKey";
                string     key        = "NZWpkyILur8B4z6djHRFcyzqGR6S7q8iVY1jtTNvzk8=";
                TimeSpan   timeSpan   = new TimeSpan(480, 30, 30);
                TokenScope tokenScope = TokenScope.Namespace;

                TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                    name, key, timeSpan, tokenScope
                    );
                NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider);

                //var qs = namespaceManager.GetQueues();
                if (!namespaceManager.QueueExists(queueName))
                {
                    QueueDescription queueDesc = new QueueDescription(queueName)
                    {
                        DefaultMessageTimeToLive = TimeSpan.FromDays(3),
                        //AutoDeleteOnIdle = TimeSpan.FromHours(1),
                        MaxSizeInMegabytes = 1024,
                        LockDuration       = TimeSpan.FromMinutes(5),
                        EnableDeadLetteringOnMessageExpiration = true,
                        RequiresDuplicateDetection             = false
                    };
                    namespaceManager.CreateQueue(queueDesc);
                }

                return(uri);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public async Task <AuthenticationResult> GetAuthAsync(TargetUri targetUri, TokenScope scope, int requestTimeout, Uri restRootUrl, Credential credentials)
        {
            // Use the provided username and password and attempt a basic authentication request to a known REST API resource.
            var result = await(new RestClient(Context)).TryGetUser(targetUri, requestTimeout, restRootUrl, credentials);

            if (result.Type.Equals(AuthenticationResultType.Success))
            {
                // Success with username/password indicates 2FA is not on so the 'token' is actually
                // the password if we had a successful call then the password is good.
                var token = new Token(credentials.Password, TokenType.Personal);
                if (!string.IsNullOrWhiteSpace(result.RemoteUsername) && !credentials.Username.Equals(result.RemoteUsername))
                {
                    Trace.WriteLine($"remote username [{result.RemoteUsername}] != [{credentials.Username}] supplied username");
                    return(new AuthenticationResult(AuthenticationResultType.Success, token, result.RemoteUsername));
                }

                return(new AuthenticationResult(AuthenticationResultType.Success, token));
            }

            Trace.WriteLine("authentication failed");
            return(result);
        }
        public Style GetStyle(TokenScope scope)
        {
            switch (scope)
            {
            case TokenScope.Comment:
                return(CommentStyle);

            case TokenScope.Keyword:
                return(KeywordStyle);

            case TokenScope.Preprocessor:
                return(PreprocessorStyle);

            case TokenScope.String:
                return(StringStyle);

            case TokenScope.Numeric:
                return(NumericStyle);

            default:
                return(KeywordStyle);
            }
        }
Exemple #16
0
 /// <summary>
 /// Construct a TokenProvider based on the provided Key Name and Shared Access Key.
 /// </summary>
 /// <param name="keyName">The key name of the corresponding SharedAccessKeyAuthorizationRule.</param>
 /// <param name="sharedAccessKey">The key associated with the SharedAccessKeyAuthorizationRule</param>
 /// <param name="tokenTimeToLive">The token time to live</param>
 /// <param name="tokenScope">The tokenScope of tokens to request.</param>
 /// <returns>A TokenProvider initialized with the provided RuleId and Password</returns>
 public static TokenProvider CreateSharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TimeSpan tokenTimeToLive, TokenScope tokenScope)
 {
     return(new SharedAccessSignatureTokenProvider(keyName, sharedAccessKey, tokenTimeToLive, tokenScope));
 }
 public TestAzureServiceBusAccountSettings()
 {
     _tokenTimeToLive = TimeSpan.FromDays(1);
     _tokenScope = TokenScope.Namespace;
 }
Exemple #18
0
 /// <summary>
 /// Generates a personal access token for use with Azure DevOps.
 /// <para/>
 /// Returns the acquired token if successful; otherwise <see langword="null"/>;
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator of the resource access tokens are being requested for.</param>
 /// <param name="accessToken">Access token granted by the identity authority (Azure).</param>
 /// <param name="tokenScope">The requested access scopes to be granted to the token.</param>
 /// <param name="requireCompactToken">`<see langword="true"/>` if requesting a compact format token; otherwise `<see langword="false"/>`.</param>
 public Task <Token> GeneratePersonalAccessToken(TargetUri targetUri, Token accessToken, TokenScope tokenScope, bool requireCompactToken)
 => GeneratePersonalAccessToken(targetUri, accessToken, tokenScope, requireCompactToken, null);
 public BasicAzureServiceBusAccountSettings()
 {
     _tokenTimeToLive = TimeSpan.FromDays(1);
     _tokenScope      = TokenScope.Namespace;
 }
Exemple #20
0
 internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TimeSpan tokenTimeToLive, TokenScope tokenScope = TokenScope.Entity)
     : this(keyName, sharedAccessKey, MessagingTokenProviderKeyEncoder, tokenTimeToLive, tokenScope)
 {
 }
        private string GetAuthorizationUrl(TokenScope scope)
        {
            var authorityUrl = $"{AuthorizeUri}?response_type=code&client_id={ConsumerKey}&state=authenticated&scope={scope.ToString()}&redirect_uri={CallbackUri}";

            return(new Uri(new Uri("https://bitbucket.org"), authorityUrl).AbsoluteUri);
        }
Exemple #22
0
        public bool VerifyToken(TokenScope Scope, String token)
        {
            string Token = ScopeToTokenMap[Scope];

            return(token == Token);
        }
 /// <summary>
 /// Generates a personal access token for use with Visual Studio Team Services.
 /// <para/>
 /// Returns the acquired token if successful; otherwise <see langword="null"/>;
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator of the resource access tokens are being requested for.</param>
 /// <param name="accessToken">Access token granted by the identity authority (Azure).</param>
 /// <param name="tokenScope">The requested access scopes to be granted to the token.</param>
 /// <param name="requireCompactToken">`<see langword="true"/>` if requesting a compact format token; otherwise `<see langword="false"/>`.</param>
 /// <param name="tokenDuration">
 /// The requested lifetime of the requested token.
 /// <para/>
 /// The authority granting the token decides the actual lifetime of any token granted, regardless of the duration requested.
 /// </param>
 public async Task <Token> GeneratePersonalAccessToken(TargetUri targetUri, Token accessToken, TokenScope tokenScope, bool requireCompactToken, TimeSpan?tokenDuration)
 {
     return(await Task.FromResult(new Token("personal-access-token", TokenType.Personal)));
 }
 /// <summary>
 /// Construct a TokenProvider based on the provided Key Name and Shared Access Key.
 /// </summary>
 /// <param name="keyName">The key name of the corresponding SharedAccessKeyAuthorizationRule.</param>
 /// <param name="sharedAccessKey">The key associated with the SharedAccessKeyAuthorizationRule</param>
 /// <param name="tokenScope">The tokenScope of tokens to request.</param>
 /// <returns>A TokenProvider initialized with the provided RuleId and Password</returns>
 public static TokenProvider CreateSharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope)
 {
     return(new SharedAccessSignatureTokenProvider(keyName, sharedAccessKey, DefaultTokenTimeout, tokenScope));
 }
 /// <summary></summary>
 /// <param name="tokenScope"></param>
 protected TokenProvider(TokenScope tokenScope)
 {
     this.TokenScope = tokenScope;
     this.ThisLock   = new object();
 }
 internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope = TokenScope.Entity)
     : this(keyName, sharedAccessKey, s_messagingTokenProviderKeyEncoder, s_defaultTokenTimeout, tokenScope)
 {
 }
        /// <summary>
        /// Gets the OAuth access token
        /// </summary>
        /// <returns>The access token</returns>
        /// <exception cref="SourceTree.Exceptions.OAuthException">
        /// Thrown when OAuth fails for whatever reason
        /// </exception>
        public async Task <AuthenticationResult> GetAuthAsync(TargetUri targetUri, TokenScope scope, CancellationToken cancellationToken)
        {
            var authToken = await Authorize(targetUri, scope, cancellationToken);

            return(await GetAccessToken(targetUri, authToken));
        }