/// <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> /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override void DeleteCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); Credential credentials = PersonalAccessTokenStore.ReadCredentials(targetUri); // This ought to be async, but the base type's method isn't. Task.Run(async() => { // Attempt to validate the credentials, if they're truly invalid delete them. if (!await ValidateCredentials(targetUri, credentials)) { PersonalAccessTokenStore.DeleteCredentials(targetUri); // Remove any related entries from the tenant cache because tenant change // could the be source of the invalidation, and not purging the cache will // trap the user in a limbo state of invalid credentials. // Deserialize the cache and remove any matching entry. string tenantUrl = targetUri.ToString(); var cache = await DeserializeTenantCache(); // Attempt to remove the URL entry, if successful serialize the cache. if (cache.Remove(tenantUrl)) { await SerializeTenantCache(cache); } } }).Wait(); }
/// <inheritdoc/> public override void DeleteCredentials(TargetUri targetUri, string username) { BaseSecureStore.ValidateTargetUri(targetUri); Trace.WriteLine("BitbucketAuthentication::DeleteCredentials"); Credential credentials = null; if ((credentials = PersonalAccessTokenStore.ReadCredentials(targetUri)) != null) { // try to delete the credentials for the explicit target uri first PersonalAccessTokenStore.DeleteCredentials(targetUri); Trace.WriteLine($"host credentials deleted for {targetUri.ActualUri}"); } // tidy up and refresh tokens var refreshTargetUri = GetRefreshTokenTargetUri(targetUri); if ((credentials = PersonalAccessTokenStore.ReadCredentials(refreshTargetUri)) != null) { // try to delete the credentials for the explicit target uri first PersonalAccessTokenStore.DeleteCredentials(refreshTargetUri); Trace.WriteLine($"host refresh credentials deleted for {refreshTargetUri.ActualUri}"); } }
/// <summary> /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override async Task <bool> DeleteCredentials(TargetUri targetUri) { if (targetUri is null) { throw new ArgumentNullException(nameof(targetUri)); } Credential credentials = await PersonalAccessTokenStore.ReadCredentials(targetUri); // Attempt to validate the credentials, if they're truly invalid delete them. if (!await ValidateCredentials(targetUri, credentials)) { await PersonalAccessTokenStore.DeleteCredentials(targetUri); // Remove any related entries from the tenant cache because tenant change // could the be source of the invalidation, and not purging the cache will // trap the user in a limbo state of invalid credentials. // Deserialize the cache and remove any matching entry. string tenantUrl = targetUri.ToString(); var cache = await DeserializeTenantCache(Context); // Attempt to remove the URL entry, if successful serialize the cache. if (cache.Remove(tenantUrl)) { await SerializeTenantCache(Context, cache); } return(true); } return(false); }
/// <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); }
/// <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)); }
/// <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)); }
/// <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); }
/// <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); }
/// <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); }
/// <summary> /// Gets a <see cref="Credential"/> from the storage used by the authentication object. /// <para/> /// Returns a `<see cref="Credential"/>` if successful; otherwise `<see langword="null"/>`. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override Credential GetCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); Credential credentials = null; if ((credentials = PersonalAccessTokenStore.ReadCredentials(targetUri)) != null) { Trace.WriteLine("successfully retrieved stored credentials, updating credential cache"); return(credentials); } // try for a refresh token var refreshCredentials = PersonalAccessTokenStore.ReadCredentials(GetRefreshTokenTargetUri(targetUri)); if (refreshCredentials == null) { // no refresh token return null return(credentials); } Credential refreshedCredentials = Task.Run(() => RefreshCredentials(targetUri, refreshCredentials.Password, null)).Result; if (refreshedCredentials == null) { // refresh failed return null return(credentials); } else { credentials = refreshedCredentials; } return(credentials); }
/// <summary> /// Gets a <see cref="Credential"/> from the storage used by the authentication object. /// <para/> /// Returns a `<see cref="Credential"/>` if successful; otherwise `<see langword="null"/>`. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override async Task <Credential> GetCredentials(TargetUri targetUri) { if (targetUri is null) { throw new ArgumentNullException(nameof(targetUri)); } Credential credentials = null; try { if ((credentials = await PersonalAccessTokenStore.ReadCredentials(targetUri)) != null) { Trace.WriteLine($"credentials for '{targetUri}' found."); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception); Trace.WriteLine($"failed to read credentials from the secure store: {exception.GetType().Name}."); } return(credentials); }
/// <summary> /// Deletes a set of stored credentials by their target resource. /// </summary> /// <param name="targetUri">The 'key' by which to identify credentials.</param> public override void DeleteCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); if (PersonalAccessTokenStore.ReadCredentials(targetUri) != null) { PersonalAccessTokenStore.DeleteCredentials(targetUri); } }
/// <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); }
/// <summary> /// Deletes a <see cref="Credential"/> from the storage used by the authentication object. /// </summary> /// <param name="targetUri"> /// The uniform resource indicator used to uniquely identify the credentials. /// </param> public override void DeleteCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); if (PersonalAccessTokenStore.ReadCredentials(targetUri) != null) { PersonalAccessTokenStore.DeleteCredentials(targetUri); Git.Trace.WriteLine($"credentials for '{targetUri}' deleted"); } }
/// <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> /// 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); }
/// <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); }
/// <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)); }
/// <summary> /// Attempts to get a set of credentials from storage by their target resource. /// </summary> /// <param name="targetUri">The 'key' by which to identify credentials.</param> /// <param name="credentials"> /// Credentials associated with the URI if successful; <see langword="null"/> otherwise. /// </param> /// <returns><see langword="true"/> if successful; <see langword="false"/> otherwise.</returns> public override Credential GetCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); Credential credentials = null; if ((credentials = PersonalAccessTokenStore.ReadCredentials(targetUri)) != null) { Git.Trace.WriteLine($"credentials for '{targetUri}' found."); } return(credentials); }
/// <inheritdoc/> public override async Task <bool> DeleteCredentials(TargetUri targetUri, string username) { if (targetUri is null) { throw new ArgumentNullException(nameof(targetUri)); } Trace.WriteLine($"Deleting Bitbucket Credentials for {targetUri.QueryUri}"); Credential credentials = null; if ((credentials = await PersonalAccessTokenStore.ReadCredentials(targetUri)) != null) { // try to delete the credentials for the explicit target uri first await PersonalAccessTokenStore.DeleteCredentials(targetUri); Trace.WriteLine($"host credentials deleted for {targetUri.QueryUri}"); } // tidy up and delete any related refresh tokens var refreshTargetUri = GetRefreshTokenTargetUri(targetUri); if ((credentials = await PersonalAccessTokenStore.ReadCredentials(refreshTargetUri)) != null) { // try to delete the credentials for the explicit target uri first await PersonalAccessTokenStore.DeleteCredentials(refreshTargetUri); Trace.WriteLine($"host refresh credentials deleted for {refreshTargetUri.QueryUri}"); } // if we deleted per user then we should try and delete the host level credentials too if // they match the username if (targetUri.TargetUriContainsUsername) { var hostTargetUri = new TargetUri(targetUri.ToString(false, true, true)); var hostCredentials = await GetCredentials(hostTargetUri); var encodedUsername = Uri.EscapeDataString(targetUri.TargetUriUsername); if (encodedUsername != username) { Trace.WriteLine($"username {username} != targetUri userInfo {encodedUsername}"); } if (hostCredentials != null && hostCredentials.Username.Equals(encodedUsername)) { await DeleteCredentials(hostTargetUri, username); } } return(true); }
/// <summary> /// Gets a <see cref="Credential"/> from the storage used by the authentication object. /// <para/> /// Returns a `<see cref="Credential"/>` if successful; otherwise `<see langword="null"/>`. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override async Task <Credential> GetCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); Credential credentials = null; var normalizedTargetUri = NormalizeUri(targetUri); if ((credentials = await PersonalAccessTokenStore.ReadCredentials(normalizedTargetUri)) != null) { Trace.WriteLine($"credentials for '{normalizedTargetUri}' found."); } return(credentials); }
/// <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); }
/// <summary> /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override async Task <bool> DeleteCredentials(TargetUri targetUri) { BaseSecureStore.ValidateTargetUri(targetUri); bool result = false; var normalizedTargetUri = NormalizeUri(targetUri); if (await PersonalAccessTokenStore.ReadCredentials(normalizedTargetUri) != null) { result = await PersonalAccessTokenStore.DeleteCredentials(normalizedTargetUri); Trace.WriteLine($"credentials for '{normalizedTargetUri}' deleted"); } return(result); }
/// <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)); }
/// <summary> /// Returns a `<see cref="Credential"/>` from the storage used by the authentication object if successful; otherwise `<see langword="null"/>`. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override async Task <Credential> GetCredentials(TargetUri targetUri) { if (targetUri is null) { throw new ArgumentNullException(nameof(targetUri)); } Credential credentials = null; var normalizedTargetUri = NormalizeUri(targetUri); if ((credentials = await PersonalAccessTokenStore.ReadCredentials(normalizedTargetUri)) != null) { Trace.WriteLine($"credentials for '{normalizedTargetUri}' found."); } return(credentials); }
/// <inheritdoc/> public override void DeleteCredentials(TargetUri targetUri, string username) { BaseSecureStore.ValidateTargetUri(targetUri); Trace.WriteLine($"Deleting Bitbucket Credentials for {targetUri.ActualUri}"); Credential credentials = null; if ((credentials = PersonalAccessTokenStore.ReadCredentials(targetUri)) != null) { // try to delete the credentials for the explicit target uri first PersonalAccessTokenStore.DeleteCredentials(targetUri); Trace.WriteLine($"host credentials deleted for {targetUri.ActualUri}"); } // tidy up and delete any related refresh tokens var refreshTargetUri = GetRefreshTokenTargetUri(targetUri); if ((credentials = PersonalAccessTokenStore.ReadCredentials(refreshTargetUri)) != null) { // try to delete the credentials for the explicit target uri first PersonalAccessTokenStore.DeleteCredentials(refreshTargetUri); Trace.WriteLine($"host refresh credentials deleted for {refreshTargetUri.ActualUri}"); } // if we deleted per user then we shoudl try and delete the host level credentials too if // they match the username if (targetUri.TargetUriContainsUsername) { var hostTargetUri = targetUri.GetHostTargetUri(); var hostCredentials = GetCredentials(hostTargetUri); var encodedUsername = Uri.EscapeDataString(targetUri.TargetUriUsername); if (encodedUsername != username) { Trace.WriteLine($"username {username} != targetUri userInfo {encodedUsername}"); } if (hostCredentials != null && hostCredentials.Username.Equals(encodedUsername)) { DeleteCredentials(targetUri.GetHostTargetUri(), username); } } }
/// <summary> /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object. /// </summary> /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param> public override async Task <bool> DeleteCredentials(TargetUri targetUri) { if (targetUri is null) { throw new ArgumentNullException(nameof(targetUri)); } bool result = false; var normalizedTargetUri = NormalizeUri(targetUri); if (await PersonalAccessTokenStore.ReadCredentials(normalizedTargetUri) != null) { result = await PersonalAccessTokenStore.DeleteCredentials(normalizedTargetUri); Trace.WriteLine($"credentials for '{normalizedTargetUri}' deleted"); } return(result); }
/// <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); }