CredentialStore

Namespace: NuGet.Core
We found 10 examples in language CSharp for this search. You will see 33 fragments of code.
    
        public IList<Credential> ListAllCredentials()
        {
            return this.credentialStore.GetAll().ToList();
        }

        public IList<Credential> FindByName(string name, bool matchExactly)
        {
            var query = this.credentialStore.GetAll();
            query = matchExactly
                ? query.Where(x => x.ServiceName == name)
                : query.Where(x => x.ServiceName.Contains(name));
            return query.ToList();
        }

        public string ShowPassword(string serviceName, string login = null)
        {
            var credential = this.credentialStore.GetAll()
                .SingleOrDefault(x => x.ServiceName == serviceName && x.Login == login);
            var key = this.userIdentity.GetUserKey();

            return credential != null
                ? CryptographyUtils.Decrypt(key, credential.Password)
                : null;
        }

        private Credential FindCredential(string serviceName, string login)
        {
            return this.credentialStore
                .GetAll()
                .SingleOrDefault(x => x.ServiceName == serviceName && x.Login == login);
        }


        public async Task Apply(IRequest request)
        {
            request.ArgumentNotNull(nameof(request));

            var credentials = await CredentialStore.GetCredentials().ConfigureAwait(false) ?? Credentials.Anonymous;

            Authenticators[credentials.AuthenticationType].Authenticate(request, credentials);
        }


        public async Task Apply(IRequest request)
        {
            var credentials = await CredentialStore.GetCredentials().ConfigureAwait(false);
            authenticators[credentials.AuthenticationType].Authenticate(request, credentials);
        }

        [TestMethod]
        public async Task SuccessfullSignIn_RaisesUserChangedEvent()
        {
            bool userChangedFired = false;

            var identityService = new MockIdentityService();
            var sessionStateService = new MockSessionStateService();
            identityService.LogOnAsyncDelegate = (userId, password) =>
                {
                    return Task.FromResult(new LogOnResult { UserInfo = new UserInfo{UserName = userId} });
                };

            var target = new AccountService(identityService, sessionStateService, null);
            target.UserChanged += (sender, userInfo) => { userChangedFired = true; }; 

            var retVal = await target.SignInUserAsync("TestUserName", "TestPassword", false);
            Assert.IsTrue(retVal);
            Assert.IsTrue(userChangedFired);
        }

        [TestMethod]
        public async Task GetSignedInUserAsync_Calls_VerifyActiveSessionAsync()
        {
            bool verifyActiveSessionCalled = false;
            var sessionStateService = new MockSessionStateService();
            var identityService = new MockIdentityService()
                {
                    LogOnAsyncDelegate = (userId, password) => Task.FromResult(new LogOnResult { UserInfo = new UserInfo { UserName = userId } }),
                    VerifyActiveSessionDelegate = (userName) =>
                        {
                            verifyActiveSessionCalled = true;
                            return Task.FromResult(true);
                        }
                };

            var target = new AccountService(identityService, sessionStateService, null);
            await target.SignInUserAsync("TestUserName", "TestPassword", false);
            var user = await target.VerifyUserAuthenticationAsync();

            Assert.IsTrue(verifyActiveSessionCalled);
            Assert.IsNotNull(user);
            Assert.IsTrue(user.UserName == "TestUserName");
        }

        [TestMethod]
        public async Task GetSignedInUserAsync_SignsInUsingCredentialStore_IfNoActiveSession()
        {
            var sessionStateService = new MockSessionStateService();
            var identityService = new MockIdentityService()
            {
                LogOnAsyncDelegate = (userId, password) => Task.FromResult(new LogOnResult { UserInfo = new UserInfo { UserName = userId } }),
                VerifyActiveSessionDelegate = (userName) => Task.FromResult(false)
            };
            var credentialStore = new MockCredentialStore()
                {
                    GetSavedCredentialsDelegate = (s) => new PasswordCredential(AccountService.PasswordVaultResourceName, "TestUserName", "TestPassword"),
                    SaveCredentialsDelegate = (a, b, c) => Task.Delay(0)
                };

            var target = new AccountService(identityService, sessionStateService, credentialStore);
            await target.SignInUserAsync("TestUserName", "TestPassword", true);

            var user = await target.VerifyUserAuthenticationAsync();

            Assert.IsNotNull(user);
            Assert.IsTrue(user.UserName == "TestUserName");
        }

        [TestMethod]
        public async Task FailedSignIn_DoesNotRaiseUserChangedEvent()
        {
            bool userChangedFired = false;

            var identityService = new MockIdentityService();
            var sessionStateService = new MockSessionStateService();
            identityService.LogOnAsyncDelegate = (userId, password) =>
            {
                throw new Exception();
            };

            var target = new AccountService(identityService, sessionStateService, null);
            target.UserChanged += (sender, userInfo) => { userChangedFired = true; };

            var retVal = await target.SignInUserAsync("TestUserName", "TestPassword", false);
            Assert.IsFalse(retVal);
            Assert.IsFalse(userChangedFired);
        }

        [TestMethod]
        public async Task CheckIfUserSignedIn_ReturnsUserInfo_IfSessionIsStillLive()
        {
            var sessionStateService = new MockSessionStateService();
            var identityService = new MockIdentityService();
            identityService.VerifyActiveSessionDelegate = (userName) => Task.FromResult(true);
            identityService.LogOnAsyncDelegate = (userName, password) =>
                {
                    return Task.FromResult(new LogOnResult()
                        {
                            UserInfo = new UserInfo() {UserName = "TestUsername"}
                        });
                };

            var target = new AccountService(identityService, sessionStateService, null);
            bool userSignedIn = await target.SignInUserAsync("TestUsername", "password", false);

            Assert.IsTrue(userSignedIn);

            var userInfo = await target.VerifyUserAuthenticationAsync();

            Assert.IsNotNull(userInfo);
        }

        [TestMethod]
        public async Task CheckIfUserSignedIn_ReturnsNull_IfSessionIsStillInactiveAndNoSavedCredentials()
        {
            var identityService = new MockIdentityService();
            identityService.VerifyActiveSessionDelegate = (userName) => Task.FromResult(false);
            var credentialStore = new MockCredentialStore();
            credentialStore.GetSavedCredentialsDelegate = s => null;
            var sessionStateService = new MockSessionStateService();
            var target = new AccountService(identityService, sessionStateService, credentialStore);

            var userInfo = await target.VerifyUserAuthenticationAsync(); 
            
            Assert.IsNull(userInfo);
        }


        public ICredentials GetCredentials(Uri uri)
        {
            Uri rootUri = GetRootUri(uri);

            ICredentials credentials;
            if (_credentialCache.TryGetValue(uri, out credentials) ||
                _credentialCache.TryGetValue(rootUri, out credentials))
            {
                return credentials;
            }

            return null;
        }

        public void Add(Uri uri, ICredentials credentials)
        {
            Uri rootUri = GetRootUri(uri);
            _credentialCache.TryAdd(uri, credentials);
            _credentialCache.AddOrUpdate(rootUri, credentials, (u, c) => credentials);
        }

        internal static Uri GetRootUri(Uri uri)
        {
            return new Uri(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
        }


        public async Task Apply(IRequest request)
        {
            Ensure.ArgumentNotNull(request, "request");

            var credentials = await CredentialStore.GetCredentials().ConfigureAwait(false) ?? Credentials.Anonymous;
            authenticators[credentials.AuthenticationType].Authenticate(request, credentials);
        }


        public ICredentials GetCredentials(Uri uri)
        {
            Uri rootUri = UriUtility.GetRootUri(uri);

            ICredentials credentials;
            if (_credentialCache.TryGetValue(uri, out credentials) ||
                _credentialCache.TryGetValue(rootUri, out credentials))
            {
                return credentials;
            }

            return null;
        }

        public void Add(Uri uri, ICredentials credentials)
        {
            Uri rootUri = UriUtility.GetRootUri(uri);
            _credentialCache.TryAdd(uri, credentials);
            _credentialCache.AddOrUpdate(rootUri, credentials, (u, c) => credentials);
        }

        [TestMethod]
        public async Task SuccessfullSignIn_RaisesUserChangedEvent()
        {
            bool userChangedFired = false;

            var identityService = new MockIdentityService();
            var sessionStateService = new MockSessionStateService();
            identityService.LogOnAsyncDelegate = (userId, password) =>
                {
                    return Task.FromResult(new LogOnResult { UserInfo = new UserInfo{UserName = userId} });
                };

            var target = new AccountService(identityService, sessionStateService, null);
            target.UserChanged += (sender, userInfo) => { userChangedFired = true; }; 

            var retVal = await target.SignInUserAsync("TestUserName", "TestPassword", false);
            Assert.IsTrue(retVal);
            Assert.IsTrue(userChangedFired);
        }

        [TestMethod]
        public async Task GetSignedInUserAsync_Calls_VerifyActiveSessionAsync()
        {
            bool verifyActiveSessionCalled = false;
            var sessionStateService = new MockSessionStateService();
            var identityService = new MockIdentityService()
                {
                    LogOnAsyncDelegate = (userId, password) => Task.FromResult(new LogOnResult { UserInfo = new UserInfo { UserName = userId } }),
                    VerifyActiveSessionDelegate = (userName) =>
                        {
                            verifyActiveSessionCalled = true;
                            return Task.FromResult(true);
                        }
                };

            var target = new AccountService(identityService, sessionStateService, null);
            await target.SignInUserAsync("TestUserName", "TestPassword", false);
            var user = await target.VerifyUserAuthenticationAsync();

            Assert.IsTrue(verifyActiveSessionCalled);
            Assert.IsNotNull(user);
            Assert.IsTrue(user.UserName == "TestUserName");
        }

        [TestMethod]
        public async Task GetSignedInUserAsync_SignsInUsingCredentialStore_IfNoActiveSession()
        {
            var sessionStateService = new MockSessionStateService();
            var identityService = new MockIdentityService()
            {
                LogOnAsyncDelegate = (userId, password) => Task.FromResult(new LogOnResult { UserInfo = new UserInfo { UserName = userId } }),
                VerifyActiveSessionDelegate = (userName) => Task.FromResult(false)
            };
            var credentialStore = new MockCredentialStore()
                {
                    GetSavedCredentialsDelegate = (s) => new PasswordCredential(AccountService.PasswordVaultResourceName, "TestUserName", "TestPassword"),
                    SaveCredentialsDelegate = (a, b, c) => Task.Delay(0)
                };

            var target = new AccountService(identityService, sessionStateService, credentialStore);
            await target.SignInUserAsync("TestUserName", "TestPassword", true);

            var user = await target.VerifyUserAuthenticationAsync();

            Assert.IsNotNull(user);
            Assert.IsTrue(user.UserName == "TestUserName");
        }

        [TestMethod]
        public async Task FailedSignIn_DoesNotRaiseUserChangedEvent()
        {
            bool userChangedFired = false;

            var identityService = new MockIdentityService();
            var sessionStateService = new MockSessionStateService();
            identityService.LogOnAsyncDelegate = (userId, password) =>
            {
                throw new Exception();
            };

            var target = new AccountService(identityService, sessionStateService, null);
            target.UserChanged += (sender, userInfo) => { userChangedFired = true; };

            var retVal = await target.SignInUserAsync("TestUserName", "TestPassword", false);
            Assert.IsFalse(retVal);
            Assert.IsFalse(userChangedFired);
        }

        [TestMethod]
        public async Task CheckIfUserSignedIn_ReturnsUserInfo_IfSessionIsStillLive()
        {
            var sessionStateService = new MockSessionStateService();
            var identityService = new MockIdentityService();
            identityService.VerifyActiveSessionDelegate = (userName) => Task.FromResult(true);
            identityService.LogOnAsyncDelegate = (userName, password) =>
                {
                    return Task.FromResult(new LogOnResult()
                        {
                            UserInfo = new UserInfo() {UserName = "TestUsername"}
                        });
                };

            var target = new AccountService(identityService, sessionStateService, null);
            bool userSignedIn = await target.SignInUserAsync("TestUsername", "password", false);

            Assert.IsTrue(userSignedIn);

            var userInfo = await target.VerifyUserAuthenticationAsync();

            Assert.IsNotNull(userInfo);
        }

        [TestMethod]
        public async Task CheckIfUserSignedIn_ReturnsNull_IfSessionIsStillInactiveAndNoSavedCredentials()
        {
            var identityService = new MockIdentityService();
            identityService.VerifyActiveSessionDelegate = (userName) => Task.FromResult(false);
            var credentialStore = new MockCredentialStore();
            credentialStore.GetSavedCredentialsDelegate = s => null;
            var sessionStateService = new MockSessionStateService();
            var target = new AccountService(identityService, sessionStateService, credentialStore);

            var userInfo = await target.VerifyUserAuthenticationAsync(); 
            
            Assert.IsNull(userInfo);
        }

        #region GetCredentialAsync

        [Fact]
        public async Task HostProvider_GetCredentialAsync_CredentialExists_ReturnsExistingCredential()
        {
            const string testUserName = "john.doe";
            const string testPassword = "letmein123";
            const string testCredentialKey = "git:test-cred-key";
            var input = new InputArguments(new Dictionary<string, string>
            {
                ["username"] = testUserName,
                ["password"] = testPassword,
            });

            var context = new TestCommandContext
            {
                CredentialStore = {[testCredentialKey] = new GitCredential(testUserName, testPassword)}
            };
            var provider = new TestHostProvider(context)
            {
                IsSupportedFunc = _ => true,
                CredentialKey = testCredentialKey,
                GenerateCredentialFunc = _ =>
                {
                    Assert.True(false, "Should never be called");
                    return null;
                },
            };

            ICredential actualCredential = await ((IHostProvider) provider).GetCredentialAsync(input);

            Assert.Equal(testUserName, actualCredential.UserName);
            Assert.Equal(testPassword, actualCredential.Password);
        }

        [Fact]
        public async Task HostProvider_GetCredentialAsync_CredentialDoesNotExist_ReturnsNewGeneratedCredential()
        {
            const string testUserName = "john.doe";
            const string testPassword = "letmein123";
            const string testCredentialKey = "git:test-cred-key";
            var input = new InputArguments(new Dictionary<string, string>
            {
                ["username"] = testUserName,
                ["password"] = testPassword,
            });

            bool generateWasCalled = false;
            var context = new TestCommandContext();
            var provider = new TestHostProvider(context)
            {
                IsSupportedFunc = _ => true,
                CredentialKey = testCredentialKey,
                GenerateCredentialFunc = _ =>
                {
                    generateWasCalled = true;
                    return new GitCredential(testUserName, testPassword);
                },
            };

            ICredential actualCredential = await ((IHostProvider) provider).GetCredentialAsync(input);

            Assert.True(generateWasCalled);
            Assert.Equal(testUserName, actualCredential.UserName);
            Assert.Equal(testPassword, actualCredential.Password);
        }


            #endregion

        #region StoreCredentialAsync

        [Fact]
        public async Task HostProvider_StoreCredentialAsync_EmptyCredential_DoesNotStoreCredential()
        {
            const string emptyUserName = "";
            const string emptyPassword = "";
            const string testCredentialKey = "git:test-cred-key";
            var input = new InputArguments(new Dictionary<string, string>
            {
                ["username"] = emptyUserName,
                ["password"] = emptyPassword,
            });

            var context = new TestCommandContext();
            var provider = new TestHostProvider(context) {CredentialKey = testCredentialKey};

            await ((IHostProvider) provider).StoreCredentialAsync(input);

            Assert.Empty(context.CredentialStore);
        }

        [Fact]
        public async Task HostProvider_StoreCredentialAsync_NonEmptyCredential_StoresCredential()
        {
            const string testUserName = "john.doe";
            const string testPassword = "letmein123";
            const string testCredentialKey = "git:test-cred-key";
            var input = new InputArguments(new Dictionary<string, string>
            {
                ["username"] = testUserName,
                ["password"] = testPassword,
            });

            var context = new TestCommandContext();
            var provider = new TestHostProvider(context) {CredentialKey = testCredentialKey};

            await ((IHostProvider) provider).StoreCredentialAsync(input);

            Assert.Single(context.CredentialStore);
            Assert.True(context.CredentialStore.TryGetValue(testCredentialKey, out ICredential storedCredential));
            Assert.Equal(testUserName, storedCredential.UserName);
            Assert.Equal(testPassword, storedCredential.Password);
        }

        [Fact]
        public async Task HostProvider_StoreCredentialAsync_NonEmptyCredential_ExistingCredential_UpdatesCredential()
        {
            const string testUserName = "john.doe";
            const string testPasswordOld = "letmein123-old";
            const string testPasswordNew = "letmein123-new";
            const string testCredentialKey = "git:test-cred-key";
            var input = new InputArguments(new Dictionary<string, string>
            {
                ["username"] = testUserName,
                ["password"] = testPasswordNew,
            });

            var context = new TestCommandContext
            {
                CredentialStore = {[testCredentialKey] = new GitCredential(testUserName, testPasswordOld)}
            };
            var provider = new TestHostProvider(context) {CredentialKey = testCredentialKey};

            await ((IHostProvider) provider).StoreCredentialAsync(input);

            Assert.Single(context.CredentialStore);
            Assert.True(context.CredentialStore.TryGetValue(testCredentialKey, out ICredential storedCredential));
            Assert.Equal(testUserName, storedCredential.UserName);
            Assert.Equal(testPasswordNew, storedCredential.Password);
        }

        #endregion

        #region EraseCredentialAsync

        [Fact]
        public async Task HostProvider_EraseCredentialAsync_NoInputUserPass_CredentialExists_ErasesCredential()
        {
            const string testCredentialKey = "git:test-cred-key";
            const string otherCredentialKey1 = "git:credential1";
            const string otherCredentialKey2 = "git:credential2";
            var input = new InputArguments(new Dictionary<string, string>());

            var context = new TestCommandContext
            {
                CredentialStore =
                {
                    [testCredentialKey] = new GitCredential("john.doe", "letmein123"),
                    [otherCredentialKey1] = new GitCredential("this.should-1", "not.be.erased-1"),
                    [otherCredentialKey2] = new GitCredential("this.should-2", "not.be.erased-2")
                }
            };
            var provider = new TestHostProvider(context) {CredentialKey = testCredentialKey};

            await ((IHostProvider) provider).EraseCredentialAsync(input);

            Assert.Equal(2, context.CredentialStore.Count);
            Assert.False(context.CredentialStore.ContainsKey(testCredentialKey));
            Assert.True(context.CredentialStore.ContainsKey(otherCredentialKey1));
            Assert.True(context.CredentialStore.ContainsKey(otherCredentialKey2));
        }


        public ICredentials GetCredentials(Uri uri)
        {
            Uri rootUri = GetRootUri(uri);

            ICredentials credentials;
            if (_credentialCache.TryGetValue(uri, out credentials) ||
                _credentialCache.TryGetValue(rootUri, out credentials))
            {
                return credentials;
            }

            return null;
        }

        public void Add(Uri uri, ICredentials credentials)
        {
            Uri rootUri = GetRootUri(uri);
            _credentialCache.TryAdd(uri, credentials);
            _credentialCache.AddOrUpdate(rootUri, credentials, (u, c) => credentials);
        }

        internal static Uri GetRootUri(Uri uri)
        {
            return new Uri(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
        }

NuGet.CredentialStore : ICredentialCache

Constructors :

public CredentialStore()

Methods :

public static CredentialStore get_Instance()
public ICredentials GetCredentials(Uri uri = )
public Void Add(Uri uri = , ICredentials credentials = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods