Пример #1
0
        internal static async Task SignRequest(this HttpRequestMessage request, ICredentialsProvider credentialsProvider, string region)
        {
            if (request == null)
            {
                throw new ArgumentException("HttpRequestMessage is null");
            }

            if (credentialsProvider == null)
            {
                throw new Exception("CredentialsProvider is null. Probably because it is not registered in IoC");
            }

            var body = VerbCanContainBody(request) ?
                       await ExtractBody(request) :
                       null;

            var credentials = credentialsProvider.GetCredentials();

            if (credentials == null)
            {
                throw new Exception("Unable to retrieve credentials required to sign the request.");
            }

            SignV4Util.SignRequest(request, body, credentials, region, "execute-api");
        }
Пример #2
0
        public TeamFoundationServer(string url, ICredentialsProvider creds)
        {
            this.uri  = new Uri(url);
            this.name = this.uri.Host;

            credentials = creds.GetCredentials(Uri, null);
        }
Пример #3
0
        private static IAmazonDynamoDB CreateClient(
            ICredentialsProvider credentialsProvider,
            IDynamoDbOptions <T> options
            )
        {
            AWSCredentials credentials = credentialsProvider.GetCredentials(options.CredentialsProfile);

            if (!string.IsNullOrWhiteSpace(options.Role))
            {
                credentials = credentialsProvider.AssumeRole(
                    credentials,
                    options.Role
                    );
            }

            if (!string.IsNullOrWhiteSpace(options.RegionEndpoint))
            {
                AmazonDynamoDBConfig config = new AmazonDynamoDBConfig {
                    RegionEndpoint = RegionEndpoint.GetBySystemName(options.RegionEndpoint)
                };
                return(new AmazonDynamoDBClient(credentials, config));
            }

            return(new AmazonDynamoDBClient(credentials));
        }
Пример #4
0
        /// <summary>
        /// 得到管理凭证
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetManageToken(GetManageTokenParam request)
        {
            ICredentialsProvider provider = (ICredentialsProvider) new DefaultCredentialsProvider(
                (ICredentials) new DefaultCredentials(_aLiYunConfig.AccessKey,
                                                      _aLiYunConfig.SecretKey, (string)null));

            return(provider.GetCredentials().SecurityToken);
        }
        internal static void Sign(this ICredentialsProvider credentialsProvider, IRequest request, byte[] body)
        {
            var credentials = credentialsProvider.GetCredentials();

            if (credentials == null)
            {
                throw new Exception("Unable to retrieve credentials.");
            }
            var regionService = ExtractRegionAndService(request.RequestUri);

            SignV4Util.SignRequest(request, body, credentials, regionService.Item1, regionService.Item2);
        }
Пример #6
0
        private async Task SignRequest(HttpRequestMessage request)
        {
            var body = request.Method == HttpMethod.Post ? await request.Content.ReadAsByteArrayAsync() : null;

            var credentials = _credentialsProvider.GetCredentials();

            if (credentials == null)
            {
                throw new Exception("Unable to retrieve credentials required to sign the request.");
            }
            SignV4Util.SignRequest(request, body, credentials, _region, "execute-api");
        }
Пример #7
0
        private ExecutionContext CreateContext(HttpMethod method, string bucket, string key)
        {
            var builder = new ExecutionContextBuilder
            {
                Bucket      = bucket,
                Key         = key,
                Method      = method,
                Credentials = _credsProvider.GetCredentials()
            };

            builder.ResponseHandlers.Add(new ErrorResponseHandler());
            return(builder.Build());
        }
Пример #8
0
        private void RefreshCredentials()
        {
            if (!CanStartRequest)
            {
                return;
            }
            _isCredentialsProcessing.Value = true;

            _credentialsProvider
            .GetCredentials()
            .Subscribe(CompleteCredentialsRequest)
            .AddTo(_subscriptions);
        }
Пример #9
0
        protected override void PopulateRowChildren(TreeIter iter)
        {
            string path = store.GetValue(iter, ColumnIndex.Path).ToString();

            string    url       = String.Empty;
            Workspace workspace = null;

            TreeIter iterParent; TreeIter current = iter;

            while (store.IterParent(out iterParent, current))
            {
                current = iterParent;
            }

            url       = store.GetValue(current, ColumnIndex.Url).ToString();
            workspace = store.GetValue(current, ColumnIndex.Workspace) as Workspace;

            ICredentials         credentials          = credentialsProvider.GetCredentials(new Uri(url), null);
            TeamFoundationServer tfs                  = TeamFoundationServerFactory.GetServer(url, credentials);
            VersionControlServer versionControlServer = tfs.GetService(typeof(VersionControlServer)) as VersionControlServer;

            int      indx     = 0;
            ItemSpec itemSpec = new ItemSpec(path, RecursionType.OneLevel);
            ItemSet  itemSet  = versionControlServer.GetItems(itemSpec, VersionSpec.Latest,
                                                              DeletedState.NonDeleted, ItemType.Folder, false);

            foreach (Microsoft.TeamFoundation.VersionControl.Client.Item item in itemSet.Items)
            {
                if (item.ServerItem == path)
                {
                    continue;
                }

                string shortPath = item.ServerItem.Substring(item.ServerItem.LastIndexOf('/') + 1);
                bool   mapped    = workspace.IsServerPathMapped(item.ServerItem);

                Gtk.TreeIter child = SetRowValue(store, iter, indx, Images.Folder, shortPath,
                                                 url, item.ServerItem, workspace, mapped);
                store.AppendValues(child, null, "", "", "", null, true);

                indx++;
            }

            // we didn't add anything!
            if (indx == 0)
            {
                TreeIter citer; store.IterChildren(out citer, iter);
                store.Remove(ref citer);
            }
        }
Пример #10
0
		private static IAmazonCognitoIdentityProvider CreateCognitoProvider(
			ICredentialsProvider credentialsProvider,
			ICognitoOptions<T> options
		) {
			AWSCredentials credentials = credentialsProvider.GetCredentials( options.CredentialsProfile );
			if( !string.IsNullOrWhiteSpace( options.Role ) ) {
				credentials = credentialsProvider.AssumeRole(
								credentials,
								options.Role
							);
			}

			if( !string.IsNullOrWhiteSpace( options.RegionEndpoint ) ) {
				AmazonCognitoIdentityProviderConfig config = new AmazonCognitoIdentityProviderConfig {
					RegionEndpoint = RegionEndpoint.GetBySystemName( options.RegionEndpoint )
				};
				return new AmazonCognitoIdentityProviderClient( credentials, config );
			}

			return new AmazonCognitoIdentityProviderClient( credentials );
		}
Пример #11
0
        void OnPathSelectionChanged(object o, EventArgs args)
        {
            TreeIter  iter;
            TreeModel model;

            if (!((TreeSelection)o).GetSelected(out model, out iter))
            {
                return;
            }

            TreeIter iterParent;
            bool     not_root = false;
            TreeIter current  = iter;

            while (model.IterParent(out iterParent, current))
            {
                current  = iterParent;
                not_root = true;
            }

            if (not_root)
            {
                string               url         = (string)model.GetValue(current, RepositoryView.ColumnIndex.Url);
                ICredentials         credentials = credentialsProvider.GetCredentials(new System.Uri(url), null);
                TeamFoundationServer tfs         = TeamFoundationServerFactory.GetServer(url, credentials);

                currentVcs = tfs.GetService(typeof(VersionControlServer)) as VersionControlServer;
                if (currentVcs == null)
                {
                    return;
                }

                currentSelectedPath = (string)model.GetValue(iter, RepositoryView.ColumnIndex.Path);

                GdkWindow.Cursor = new Gdk.Cursor(Gdk.CursorType.Watch);
                directoryView.UpdatePath(currentVcs, currentSelectedPath);
                changesetView.UpdatePath(currentVcs, currentSelectedPath);
                GdkWindow.Cursor = null;
            }
        }
Пример #12
0
        public RepositoryView(ExploreView exploreView, ICredentialsProvider credentialsProvider)
        {
            this.exploreView         = exploreView;
            menu                     = new RepositoryMenu(exploreView);
            this.credentialsProvider = credentialsProvider;

            // setup main column with image/text data
            TreeViewColumn     column = new TreeViewColumn();
            CellRendererText   crt    = new CellRendererText();
            CellRendererPixbuf crp    = new CellRendererPixbuf();

            column.Title = "Repository";
            column.PackStart(crp, false);
            column.PackStart(crt, true);
            column.AddAttribute(crp, "pixbuf", 0);
            column.AddAttribute(crt, "text", 1);
            column.SetCellDataFunc(crt, new Gtk.TreeCellDataFunc(RenderRepositoryName));
            AppendColumn(column);

            WorkspaceInfo[] infos = Workstation.Current.GetAllLocalWorkspaceInfo();
            foreach (WorkspaceInfo info in infos)
            {
                ICredentials         credentials = credentialsProvider.GetCredentials(info.ServerUri, null);
                TeamFoundationServer tfs         = TeamFoundationServerFactory.GetServer(info.ServerUri.ToString(), credentials);
                VersionControlServer vcs         = tfs.GetService(typeof(VersionControlServer)) as VersionControlServer;

                Workspace workspace = vcs.GetWorkspace(info.Name, info.OwnerName);
                workspace.RefreshMappings();

                string       label      = String.Format("{0}@{1}", info.Name, info.ServerUri.Host.ToString());
                Gtk.TreeIter serverIter = store.AppendValues(Images.Repository, label, info.ServerUri.ToString(), VersionControlPath.RootFolder, workspace, true);
                store.AppendValues(serverIter, null, "", "", "", null, true);
            }

            Model            = store;
            HeadersVisible   = true;
            KeyReleaseEvent += MyKeyReleaseEventHandler;

            ShowAll();
        }
Пример #13
0
        public RepositoryView(ExploreView exploreView, ICredentialsProvider credentialsProvider)
        {
            this.exploreView = exploreView;
                menu = new RepositoryMenu(exploreView);
                this.credentialsProvider = credentialsProvider;

                // setup main column with image/text data
                TreeViewColumn column = new TreeViewColumn ();
                CellRendererText crt = new CellRendererText();
                CellRendererPixbuf crp = new CellRendererPixbuf();
                column.Title = "Repository";
                column.PackStart(crp, false);
                column.PackStart(crt, true);
                column.AddAttribute(crp, "pixbuf", 0);
                column.AddAttribute(crt, "text", 1);
                column.SetCellDataFunc(crt, new Gtk.TreeCellDataFunc (RenderRepositoryName));
                AppendColumn(column);

                WorkspaceInfo[] infos = Workstation.Current.GetAllLocalWorkspaceInfo();
                foreach (WorkspaceInfo info in infos)
                    {
                        ICredentials credentials = credentialsProvider.GetCredentials(info.ServerUri, null);
                        TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(info.ServerUri.ToString(), credentials);
                        VersionControlServer vcs = tfs.GetService(typeof(VersionControlServer)) as VersionControlServer;

                        Workspace workspace = vcs.GetWorkspace(info.Name, info.OwnerName);
                        workspace.RefreshMappings();

                        string label = String.Format("{0}@{1}", info.Name, info.ServerUri.Host.ToString());
                        Gtk.TreeIter serverIter = store.AppendValues(Images.Repository, label, info.ServerUri.ToString(), VersionControlPath.RootFolder, workspace, true);
                        store.AppendValues(serverIter, null, "", "", "", null, true);
                    }

                Model = store;
                HeadersVisible = true;
                KeyReleaseEvent += MyKeyReleaseEventHandler;

                ShowAll();
        }
Пример #14
0
        public void SendMail(string from, string to, string messageType, IMessageBodyDictionary body)
        {
            var temp = templateProvider.GetTemplate(messageType);

            var content = contentBuilder.BuildContent(temp, body);

            //Create message
            var message = new MimeMessage();

            message.To.Add(new MailboxAddress(to));
            message.From.Add(new MailboxAddress(from));
            message.Body = new TextPart("html")
            {
                Text = content
            };

            var cred = credentialsProvider.GetCredentials();

            smtpClient.Connect(cred.Username, cred.Password);
            smtpClient.SendMessage(message);
            smtpClient.Diconnect();
        }
        private void SignRequest(IRequest request, RequestData requestData)
        {
            byte[] data = null;
            if (requestData.PostData != null)
            {
                data = requestData.PostData.WrittenBytes;
                if (data == null)
                {
                    using (var ms = new MemoryStream())
                    {
                        requestData.PostData.Write(ms, requestData.ConnectionSettings);
                        data = ms.ToArray();
                    }
                }
            }
            var credentials = _credentialsProvider.GetCredentials();

            if (credentials == null)
            {
                throw new Exception("Unable to retrieve credentials required to sign the request.");
            }
            SignV4Util.SignRequest(request, data, credentials, _region, "es");
        }
Пример #16
0
 protected Credentials GetCredentials()
 {
     return(credentialsProvider.GetCredentials());
 }
        public bool Authenticate(ICredentialsProvider provider)
        {
            log.Info("Authenticating");
            if (provider == null)
            {
                throw new ArgumentNullException("AuthenticationInfo can not be null in order to authenticate.");
            }
            AuthenticationInfo authInfoToUse = null;

            try
            {
                authInfoToUse = provider.GetCredentials();
                if (authInfoToUse == null)
                {
                    throw new InvalidCredentialsException("Credential provider returned null");
                }
            }
            catch (InvalidCredentialsException ice)
            {
                log.Error("Failed to obtain credentials.", ice);
                return(false);
            }

            // save important information
            lock (this)
            {
                this.provider       = provider;
                this.clientAuthInfo = authInfoToUse;
                this.usingAuth      = true;
            }

            // build NetMessage

            string actionId = System.Guid.NewGuid().ToString();

            NetAuthentication netAuth = new NetAuthentication(authInfoToUse.Token, authInfoToUse.UserAuthenticationType);

            if ((authInfoToUse.Roles != null) && (authInfoToUse.Roles.Count != 0))
            {
                netAuth.Roles = authInfoToUse.Roles;
            }
            if (authInfoToUse.UserId != null)
            {
                netAuth.UserId = authInfoToUse.UserId;
            }
            netAuth.ActionId = actionId;

            NetAction netAction = new NetAction(NetAction.ActionType.AUTH);

            netAction.AuthenticationMessage = netAuth;
            NetMessage msg = new NetMessage(netAction);

            // build waitable object
            WaitMessageAccepted waitMsgAccepted = new WaitMessageAccepted();
            AcceptRequest       acceptRequest   = new AcceptRequest(actionId, waitMsgAccepted, 7000);

            //send message
            HandleOutgoingMessage(msg, acceptRequest);

            // wait for response
            lock (waitMsgAccepted.SyncObject)
            {
                Monitor.Wait(waitMsgAccepted.SyncObject);
            }
            if (waitMsgAccepted.WaitResult != WaitMessageAccepted.Result.Accepted)
            {
                log.Error("Authenticatation failed. Reason: " + waitMsgAccepted.WaitResult);
                return(false);
            }

            log.Info("Authenticated");

            return(true);
        }
Пример #18
0
        /// <inheritdoc/>
        public Uri GeneratePresignedUri(GeneratePresignedUriRequest generatePresignedUriRequest)
        {
            ThrowIfNullRequest(generatePresignedUriRequest);

            var creds         = _credsProvider.GetCredentials();
            var accessId      = creds.AccessId;
            var accessKey     = creds.AccessKey;
            var securityToken = creds.SecurityToken;
            var useToken      = creds.UseToken;
            var bucketName    = generatePresignedUriRequest.BucketName;
            var key           = generatePresignedUriRequest.Key;

            const long ticksOf1970 = 621355968000000000;
            var        expires     = ((generatePresignedUriRequest.Expiration.ToUniversalTime().Ticks - ticksOf1970) / 10000000L)
                                     .ToString(CultureInfo.InvariantCulture);
            var resourcePath = OssUtils.MakeResourcePath(key);

            var request = new ServiceRequest();
            var conf    = OssUtils.GetClientConfiguration(_serviceClient);

            request.Endpoint     = OssUtils.MakeBucketEndpoint(_endpoint, bucketName, conf);
            request.ResourcePath = resourcePath;

            switch (generatePresignedUriRequest.Method)
            {
            case SignHttpMethod.Get:
                request.Method = HttpMethod.Get;
                break;

            case SignHttpMethod.Put:
                request.Method = HttpMethod.Put;
                break;

            default:
                throw new ArgumentException("Unsupported http method.");
            }

            request.Headers.Add(HttpHeaders.Date, expires);
            if (!string.IsNullOrEmpty(generatePresignedUriRequest.ContentType))
            {
                request.Headers.Add(HttpHeaders.ContentType, generatePresignedUriRequest.ContentType);
            }
            if (!string.IsNullOrEmpty(generatePresignedUriRequest.ContentMd5))
            {
                request.Headers.Add(HttpHeaders.ContentMd5, generatePresignedUriRequest.ContentMd5);
            }

            foreach (var pair in generatePresignedUriRequest.UserMetadata)
            {
                request.Headers.Add(OssHeaders.OssUserMetaPrefix + pair.Key, pair.Value);
            }

            if (generatePresignedUriRequest.ResponseHeaders != null)
            {
                generatePresignedUriRequest.ResponseHeaders.Populate(request.Parameters);
            }

            foreach (var param in generatePresignedUriRequest.QueryParams)
            {
                request.Parameters.Add(param.Key, param.Value);
            }

            if (useToken)
            {
                request.Parameters.Add(RequestParameters.SECURITY_TOKEN, securityToken);
            }

            var canonicalResource = "/" + (bucketName ?? "") + ((key != null ? "/" + key : ""));
            var httpMethod        = generatePresignedUriRequest.Method.ToString().ToUpperInvariant();

            var canonicalString =
                SignUtils.BuildCanonicalString(httpMethod, canonicalResource, request /*, expires*/);
            var signature = ServiceSignature.Create().ComputeSignature(accessKey, canonicalString);

            IDictionary <string, string> queryParams = new Dictionary <string, string>();

            queryParams.Add(RequestParameters.EXPIRES, expires);
            queryParams.Add(RequestParameters.OSS_ACCESS_KEY_ID, accessId);
            queryParams.Add(RequestParameters.SIGNATURE, signature);
            foreach (var param in request.Parameters)
            {
                queryParams.Add(param.Key, param.Value);
            }

            var queryString = HttpUtils.ConbineQueryString(queryParams);
            var uriString   = request.Endpoint.ToString();

            if (!uriString.EndsWith("/"))
            {
                uriString += "/";
            }
            uriString += resourcePath + "?" + queryString;

            return(new Uri(uriString));
        }
        public bool Authenticate(ICredentialsProvider provider)
        {
            log.Info("Authenticating");
            if (provider == null)
            {
                throw new ArgumentNullException("AuthenticationInfo can not be null in order to authenticate.");
            }
            AuthenticationInfo authInfoToUse = null;
            try
            {
                authInfoToUse = provider.GetCredentials();
                if (authInfoToUse == null)
                    throw new InvalidCredentialsException("Credential provider returned null");
            }
            catch (InvalidCredentialsException ice)
            {
                log.Error("Failed to obtain credentials.", ice);
                return false;
            }

            // save important information
            lock (this)
            {
                this.provider = provider;
                this.clientAuthInfo = authInfoToUse;
                this.usingAuth = true;
            }

            // build NetMessage

            string actionId = System.Guid.NewGuid().ToString();

            NetAuthentication netAuth = new NetAuthentication(authInfoToUse.Token, authInfoToUse.UserAuthenticationType);
            if ((authInfoToUse.Roles != null) && (authInfoToUse.Roles.Count != 0))
                netAuth.Roles = authInfoToUse.Roles;
            if (authInfoToUse.UserId != null)
            {
                netAuth.UserId = authInfoToUse.UserId;
            }
            netAuth.ActionId = actionId;

            NetAction netAction = new NetAction(NetAction.ActionType.AUTH);
            netAction.AuthenticationMessage = netAuth;
            NetMessage msg = new NetMessage(netAction);

            // build waitable object
            WaitMessageAccepted waitMsgAccepted = new WaitMessageAccepted();
            AcceptRequest acceptRequest = new AcceptRequest(actionId, waitMsgAccepted, 7000);

            //send message
            HandleOutgoingMessage(msg, acceptRequest);

            // wait for response
            lock (waitMsgAccepted.SyncObject)
            {
                Monitor.Wait(waitMsgAccepted.SyncObject);
            }
            if (waitMsgAccepted.WaitResult != WaitMessageAccepted.Result.Accepted)
            {
                log.Error("Authenticatation failed. Reason: " + waitMsgAccepted.WaitResult);
                return false;
            }

            log.Info("Authenticated");

            return true;
        }
Пример #20
0
 private Credentials CreateCredentials()
 {
     return(credentialsProvider.GetCredentials());
 }