/// <summary>
        /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator used to uniquely identify the credentials.
        /// </param>
        /// <param name="credentials">The value to be stored.</param>
        public override Task <bool> SetCredentials(TargetUri targetUri, Credential credentials)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            BaseSecureStore.ValidateCredential(credentials);

            return(PersonalAccessTokenStore.WriteCredentials(NormalizeUri(targetUri), credentials));
        }
Beispiel #2
0
        /// <summary>
        /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator used to uniquely identify the credentials.
        /// </param>
        /// <param name="credentials">The value to be stored.</param>
        public override void SetCredentials(TargetUri targetUri, Credential credentials)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            BaseSecureStore.ValidateCredential(credentials);

            PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);
        }
        /// <inheritdoc/>
        public async Task <bool> SetCredentials(TargetUri targetUri, Credential credentials, string username)
        {
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }
            if (credentials is null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            Trace.WriteLine($"{credentials.Username} at {targetUri.QueryUri.AbsoluteUri}");

            // If the Url doesn't contain a username then save with an explicit username.
            if (!targetUri.TargetUriContainsUsername && (!string.IsNullOrWhiteSpace(username) ||
                                                         !string.IsNullOrWhiteSpace(credentials.Username)))
            {
                var        realUsername    = GetRealUsername(credentials, username);
                Credential tempCredentials = new Credential(realUsername, credentials.Password);

                if (tempCredentials.Username.Length > BaseSecureStore.UsernameMaxLength)
                {
                    throw new ArgumentOutOfRangeException(nameof(tempCredentials.Username));
                }
                if (tempCredentials.Password.Length > BaseSecureStore.PasswordMaxLength)
                {
                    throw new ArgumentOutOfRangeException(nameof(tempCredentials.Password));
                }

                await SetCredentials(targetUri.GetPerUserTargetUri(realUsername), tempCredentials, null);
            }

            return(await PersonalAccessTokenStore.WriteCredentials(targetUri, credentials));
        }
Beispiel #4
0
        /// <summary>
        /// <para></para>
        /// <para>Tokens acquired are stored in the secure secret store provided during
        /// initialization.</para>
        /// </summary>
        /// <param name="targetUri">The unique identifier for the resource for which access is to
        /// be acquired.</param>
        /// <param name="username">The username of the account for which access is to be acquired.</param>
        /// <param name="password">The password of the account for which access is to be acquired.</param>
        /// <param name="authenticationCode">The two-factor authentication code for use in access acquisition.</param>
        /// <returns>Acquired <see cref="Credential"/> if successful; otherwise <see langword="null"/>.</returns>
        public async Task <Credential> NoninteractiveLogonWithCredentials(TargetUri targetUri, string username, string password, string authenticationCode)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            if (String.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username", "The `username` parameter is null or invalid.");
            }
            if (String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("username", "The `password` parameter is null or invalid.");
            }

            Credential credentials = null;

            AuthenticationResult result;

            if (result = await Authority.AcquireToken(targetUri, username, password, authenticationCode, this.TokenScope))
            {
                Git.Trace.WriteLine($"token acquisition for '{targetUri}' succeeded.");

                credentials = (Credential)result.Token;
                PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);

                return(credentials);
            }

            Git.Trace.WriteLine($"non-interactive logon for '{targetUri}' failed.");
            return(credentials);
        }
Beispiel #5
0
        /// <summary>
        /// <para></para>
        /// <para>Tokens acquired are stored in the secure secret store provided during
        /// initialization.</para>
        /// </summary>
        /// <param name="targetUri">The unique identifier for the resource for which access is to
        /// be acquired.</param>
        /// <param name="username">The username of the account for which access is to be acquired.</param>
        /// <param name="password">The password of the account for which access is to be acquired.</param>
        /// <param name="authenticationCode">The two-factor authentication code for use in access acquision.</param>
        /// <returns>True if success; otherwise false.</returns>
        public async Task <bool> NoninteractiveLogonWithCredentials(Uri targetUri, string username, string password, string authenticationCode = null)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            if (String.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username", "The `username` parameter is null or invalid.");
            }
            if (String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("username", "The `password` parameter is null or invalid.");
            }

            Trace.WriteLine("GithubAuthentication::NoninteractiveLogonWithCredentials");

            GithubAuthenticationResult result;

            if (result = await GithubAuthority.AcquireToken(targetUri, username, password, authenticationCode, this.TokenScope))
            {
                Trace.WriteLine("   token aquisition succeeded");

                PersonalAccessTokenStore.WriteCredentials(targetUri, (Credential)result.Token);

                return(true);
            }

            Trace.WriteLine("   non-interactive logon failed");
            return(false);
        }
Beispiel #6
0
        /// <summary>
        /// Tokens acquired are stored in the secure secret store provided during initialization.
        /// <para/>
        /// Returns acquired `<see cref="Credential"/>` if successful; otherwise `<see langword="null"/>`.
        /// </summary>
        /// <param name="targetUri">The unique identifier for the resource for which access is to be acquired.</param>
        /// <param name="username">The username of the account for which access is to be acquired.</param>
        /// <param name="password">The password of the account for which access is to be acquired.</param>
        /// <param name="authenticationCode">The two-factor authentication code for use in access acquisition.</param>
        public async Task <Credential> NoninteractiveLogonWithCredentials(TargetUri targetUri, string username, string password, string authenticationCode)
        {
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }
            if (username is null)
            {
                throw new ArgumentNullException(nameof(username));
            }
            if (password is null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            Credential           credentials         = null;
            var                  normalizedTargetUri = NormalizeUri(targetUri);
            AuthenticationResult result;

            if (result = await Authority.AcquireToken(normalizedTargetUri, username, password, authenticationCode, TokenScope))
            {
                Trace.WriteLine($"token acquisition for '{normalizedTargetUri}' succeeded.");

                credentials = (Credential)result.Token;
                await PersonalAccessTokenStore.WriteCredentials(normalizedTargetUri, credentials);

                return(credentials);
            }

            Trace.WriteLine($"non-interactive logon for '{normalizedTargetUri}' failed.");
            return(credentials);
        }
Beispiel #7
0
        /// <summary>
        /// Generates a "personal access token" or service specific, usage resticted access token.
        /// </summary>
        /// <param name="targetUri">
        /// The target resource for which to acquire the personal access token for.
        /// </param>
        /// <param name="accessToken">
        /// Azure Directory access token with privileges to grant access to the target resource.
        /// </param>
        /// <param name="requestCompactToken">
        /// Generates a compact token if <see langword="true"/>; generates a self describing token if <see langword="false"/>.
        /// </param>
        /// <returns><see langword="true"/> if successful; <see langword="false"/> otherwise.</returns>
        protected async Task <Credential> GeneratePersonalAccessToken(
            TargetUri targetUri,
            Token accessToken,
            bool requestCompactToken)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);

            if (ReferenceEquals(accessToken, null))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            Credential credential = null;

            Token personalAccessToken;

            if ((personalAccessToken = await VstsAuthority.GeneratePersonalAccessToken(targetUri, accessToken, TokenScope, requestCompactToken)) != null)
            {
                credential = (Credential)personalAccessToken;

                Git.Trace.WriteLine($"personal access token created for '{targetUri}'.");

                PersonalAccessTokenStore.WriteCredentials(targetUri, credential);
            }

            return(credential);
        }
        /// <summary>
        /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator used to uniquely identify the credentials.
        /// </param>
        /// <param name="credentials">The value to be stored.</param>
        public override void SetCredentials(TargetUri targetUri, Credential credentials)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            BaseSecureStore.ValidateCredential(credentials);

            Trace.WriteLine("GitHubAuthentication::SetCredentials");

            PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);
        }
Beispiel #9
0
        /// <summary>
        /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator used to uniquely identitfy the credentials.
        /// </param>
        /// <param name="credentials">The value to be stored.</param>
        /// <returns>True if successful; otherwise false.</returns>
        public override bool SetCredentials(Uri targetUri, Credential credentials)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            Credential.Validate(credentials);

            Trace.WriteLine("GithubAuthentication::SetCredentials");

            PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);

            return(true);
        }
Beispiel #10
0
        /// <summary>
        /// Tokens acquired are stored in the secure secret store provided during initialization.
        /// <para/>
        /// Returns acquired `<see cref="Credential"/>` if successful; otherwise `<see langword="null"/>`
        /// </summary>
        /// <param name="targetUri">The unique identifier for the resource for which access is to be acquired.</param>
        public async Task <Credential> InteractiveLogon(TargetUri targetUri)
        {
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }

            Credential credentials = null;

            var normalizedTargetUri = NormalizeUri(targetUri);

            if (AcquireCredentialsCallback(normalizedTargetUri, out string username, out string password))
            {
                AuthenticationResult result;

                if (result = await Authority.AcquireToken(normalizedTargetUri, username, password, null, TokenScope))
                {
                    Trace.WriteLine($"token acquisition for '{normalizedTargetUri}' succeeded");

                    credentials = (Credential)result.Token;
                    await PersonalAccessTokenStore.WriteCredentials(normalizedTargetUri, credentials);

                    // if a result callback was registered, call it
                    AuthenticationResultCallback?.Invoke(normalizedTargetUri, result);

                    return(credentials);
                }
                else if (result == GitHubAuthenticationResultType.TwoFactorApp ||
                         result == GitHubAuthenticationResultType.TwoFactorSms)
                {
                    string authenticationCode;
                    if (AcquireAuthenticationCodeCallback(normalizedTargetUri, result, username, out authenticationCode))
                    {
                        if (result = await Authority.AcquireToken(normalizedTargetUri, username, password, authenticationCode, TokenScope))
                        {
                            Trace.WriteLine($"token acquisition for '{normalizedTargetUri}' succeeded.");

                            credentials = (Credential)result.Token;
                            await PersonalAccessTokenStore.WriteCredentials(normalizedTargetUri, credentials);

                            // if a result callback was registered, call it
                            AuthenticationResultCallback?.Invoke(normalizedTargetUri, result);

                            return(credentials);
                        }
                    }
                }

                AuthenticationResultCallback?.Invoke(normalizedTargetUri, result);
            }

            Trace.WriteLine($"interactive logon for '{normalizedTargetUri}' failed.");
            return(credentials);
        }
        /// <summary>
        /// <para></para>
        /// <para>Tokens acquired are stored in the secure secret store provided during initialization.</para>
        /// </summary>
        /// <param name="targetUri">
        /// The unique identifier for the resource for which access is to be acquired.
        /// </param>
        /// ///
        /// <returns>Acquired <see cref="Credential"/> if successful; otherwise <see langword="null"/>.</returns>
        public async Task <Credential> InteractiveLogon(TargetUri targetUri)
        {
            Credential credentials = null;
            string     username;
            string     password;

            if (AcquireCredentialsCallback(targetUri, out username, out password))
            {
                AuthenticationResult result;

                if (result = await Authority.AcquireToken(targetUri, username, password, null, TokenScope))
                {
                    Git.Trace.WriteLine($"token acquisition for '{targetUri}' succeeded");

                    credentials = (Credential)result.Token;
                    PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);

                    // if a result callback was registered, call it
                    AuthenticationResultCallback?.Invoke(targetUri, result);

                    return(credentials);
                }
                else if (result == GitHubAuthenticationResultType.TwoFactorApp ||
                         result == GitHubAuthenticationResultType.TwoFactorSms)
                {
                    string authenticationCode;
                    if (AcquireAuthenticationCodeCallback(targetUri, result, username, out authenticationCode))
                    {
                        if (result = await Authority.AcquireToken(targetUri, username, password, authenticationCode, TokenScope))
                        {
                            Git.Trace.WriteLine($"token acquisition for '{targetUri}' succeeded.");

                            credentials = (Credential)result.Token;
                            PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);

                            // if a result callback was registered, call it
                            AuthenticationResultCallback?.Invoke(targetUri, result);

                            return(credentials);
                        }
                    }
                }

                // if a result callback was registered, call it
                if (AuthenticationResultCallback != null)
                {
                    AuthenticationResultCallback(targetUri, result);
                }
            }

            Git.Trace.WriteLine($"interactive logon for '{targetUri}' failed.");
            return(credentials);
        }
        /// <summary>
        /// Generates a "personal access token" or service specific, usage restricted access token.
        /// <para/>
        /// Returns a "personal access token" for the user if successful; otherwise `<see langword="null"/>`.
        /// </summary>
        /// <param name="targetUri">The target resource for which to acquire the personal access token for.</param>
        /// <param name="accessToken">Azure Directory access token with privileges to grant access to the target resource.</param>
        /// <param name="options">Set of options related to generation of personal access tokens.</param>
        protected async Task <Credential> GeneratePersonalAccessToken(
            TargetUri targetUri,
            Token accessToken,
            PersonalAccessTokenOptions options)
        {
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }
            if (accessToken is null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            TokenScope requestedScope = TokenScope;

            if (options.TokenScope != null)
            {
                // Take the intersection of the authority scope and the requested scope
                requestedScope &= options.TokenScope;

                // If the result of the intersection is none, then fail
                if (string.IsNullOrWhiteSpace(requestedScope.Value))
                {
                    throw new InvalidOperationException("Invalid scope requested. Requested scope would result in no access privileges.");
                }
            }

            Credential credential = null;

            Token personalAccessToken;

            if ((personalAccessToken = await Authority.GeneratePersonalAccessToken(targetUri, accessToken, requestedScope, options.RequireCompactToken, options.TokenDuration)) != null)
            {
                credential = (Credential)personalAccessToken;

                Trace.WriteLine($"personal access token created for '{targetUri}'.");

                try
                {
                    await PersonalAccessTokenStore.WriteCredentials(targetUri, credential);
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Debug.WriteLine(exception);

                    Trace.WriteLine($"failed to write credentials to the secure store: {exception.GetType().Name}.");
                }
            }

            return(credential);
        }
Beispiel #13
0
        /// <summary>
        /// Sets a `<see cref="Credential"/>` in the storage used by the authentication object.
        /// <para/>
        /// Returns `<see langword="true"/>` if successful; otherwise `<see langword="false"/>`.
        /// </summary>
        /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param>
        /// <param name="credentials">The value to be stored.</param>
        public override Task <bool> SetCredentials(TargetUri targetUri, Credential credentials)
        {
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }
            if (credentials is null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            return(PersonalAccessTokenStore.WriteCredentials(NormalizeUri(targetUri), credentials));
        }
Beispiel #14
0
        /// <inheritdoc/>
        public void SetCredentials(TargetUri targetUri, Credential credentials, string username)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            BaseSecureStore.ValidateCredential(credentials);

            Trace.WriteLine($"{credentials.Username} at {targetUri.ActualUri.AbsoluteUri}");

            // if the url doesn't contain a username then save with an explicit username.
            if (!TargetUriContainsUsername(targetUri) && !string.IsNullOrWhiteSpace(username))
            {
                Credential tempCredentials = new Credential(username, credentials.Password);
                SetCredentials(GetPerUserTargetUri(targetUri, username), tempCredentials, null);
            }

            PersonalAccessTokenStore.WriteCredentials(targetUri, credentials);
        }
Beispiel #15
0
        /// <inheritdoc/>
        public async Task <bool> SetCredentials(TargetUri targetUri, Credential credentials, string username)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);
            BaseSecureStore.ValidateCredential(credentials);

            Trace.WriteLine($"{credentials.Username} at {targetUri.QueryUri.AbsoluteUri}");

            // If the Url doesn't contain a username then save with an explicit username.
            if (!targetUri.TargetUriContainsUsername && (!string.IsNullOrWhiteSpace(username) ||
                                                         !string.IsNullOrWhiteSpace(credentials.Username)))
            {
                var        realUsername    = GetRealUsername(credentials, username);
                Credential tempCredentials = new Credential(realUsername, credentials.Password);
                await SetCredentials(targetUri.GetPerUserTargetUri(realUsername), tempCredentials, null);
            }

            return(await PersonalAccessTokenStore.WriteCredentials(targetUri, credentials));
        }
Beispiel #16
0
        /// <summary>
        /// Generates a "personal access token" or service specific, usage resticted access token.
        /// </summary>
        /// <param name="targetUri">
        /// The target resource for which to acquire the personal access token for.
        /// </param>
        /// <param name="accessToken">
        /// Azure Directory access token with privileges to grant access to the target resource.
        /// </param>
        /// <param name="options">
        /// Set of options related to generation of personal access tokens.
        /// </param>
        /// <returns><see langword="true"/> if successful; <see langword="false"/> otherwise.</returns>
        protected async Task <Credential> GeneratePersonalAccessToken(
            TargetUri targetUri,
            Token accessToken,
            PersonalAccessTokenOptions options)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);

            if (ReferenceEquals(accessToken, null))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            VstsTokenScope requestedScope = TokenScope;

            if (options.TokenScope != null)
            {
                // Take the intersection of the auhority scope and the requested scope
                requestedScope &= options.TokenScope;

                // If the result of the intersection is none, then fail
                if (string.IsNullOrWhiteSpace(requestedScope.Value))
                {
                    throw new InvalidOperationException("Invalid scope requested. Reqeuested scope would result in no access privileges.");
                }
            }

            Credential credential = null;

            Token personalAccessToken;

            if ((personalAccessToken = await VstsAuthority.GeneratePersonalAccessToken(targetUri, accessToken, requestedScope, options.RequireCompactToken, options.TokenDuration)) != null)
            {
                credential = (Credential)personalAccessToken;

                Git.Trace.WriteLine($"personal access token created for '{targetUri}'.");

                PersonalAccessTokenStore.WriteCredentials(targetUri, credential);
            }

            return(credential);
        }
        /// <summary>
        /// Generates a "personal access token" or service specific, usage restricted access token.
        /// <para/>
        /// Returns `<see langword="true"/>` if successful; `<see langword="false"/>` otherwise.
        /// </summary>
        /// <param name="targetUri">The target resource for which to acquire the personal access token for.</param>
        /// <param name="accessToken">Azure Directory access token with privileges to grant access to the target resource.</param>
        /// <param name="requestCompactToken">Generates a compact token if `<see langword="true"/>`; generates a self describing token if `<see langword="false"/>`.</param>
        protected async Task <Credential> GeneratePersonalAccessToken(
            TargetUri targetUri,
            Token accessToken,
            bool requestCompactToken)
        {
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }
            if (accessToken is null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            Credential credential = null;

            Token personalAccessToken;

            if ((personalAccessToken = await Authority.GeneratePersonalAccessToken(targetUri, accessToken, TokenScope, requestCompactToken)) != null)
            {
                credential = (Credential)personalAccessToken;

                Trace.WriteLine($"personal access token created for '{targetUri}'.");

                try
                {
                    await PersonalAccessTokenStore.WriteCredentials(targetUri, credential);
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Debug.WriteLine(exception);

                    Trace.WriteLine($"failed to write credentials to the secure store.");
                    Trace.WriteException(exception);
                }
            }

            return(credential);
        }
        /// <summary>
        /// Generates a "personal access token" or service specific, usage restricted access token.
        /// <para/>
        /// Returns `<see langword="true"/>` if successful; `<see langword="false"/>` otherwise.
        /// </summary>
        /// <param name="targetUri">The target resource for which to acquire the personal access token for.</param>
        /// <param name="accessToken">Azure Directory access token with privileges to grant access to the target resource.</param>
        /// <param name="requestCompactToken">Generates a compact token if `<see langword="true"/>`; generates a self describing token if `<see langword="false"/>`.</param>
        protected async Task <Credential> GeneratePersonalAccessToken(
            TargetUri targetUri,
            Token accessToken,
            bool requestCompactToken)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);

            if (ReferenceEquals(accessToken, null))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            Credential credential = null;

            Token personalAccessToken;

            if ((personalAccessToken = await VstsAuthority.GeneratePersonalAccessToken(targetUri, accessToken, TokenScope, requestCompactToken)) != null)
            {
                credential = (Credential)personalAccessToken;

                Git.Trace.WriteLine($"personal access token created for '{targetUri}'.");

                try
                {
                    PersonalAccessTokenStore.WriteCredentials(targetUri, credential);
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Debug.WriteLine(exception);

                    Git.Trace.WriteLine($"failed to write credentials to the secure store: {exception.GetType().Name}.");
                }
            }

            return(credential);
        }