Jim*_*Jim 4 c# caching visual-studio azure-devops azure-devops-rest-api
我正在使用Visual Studio客户端工具在命令行实用程序中调用VSTS REST API。对于不同的命令(复制,删除,应用策略等),此实用程序可以运行多次。
我正在像这样创建VssConnection
public static VssConnection CreateConnection(Uri url, VssCredentials credentials = null)
{
credentials = credentials ?? new VssClientCredentials();
credentials.Storage = new VssClientCredentialStorage();
var connection = new VssConnection(url, credentials);
connection.ConnectAsync().SyncResult();
return connection;
}
Run Code Online (Sandbox Code Playgroud)
根据文档,这应该是缓存凭据,以便在运行命令行工具时不会再次提示您。但是,每当我运行命令行实用程序并且VssConnection尝试连接时,我都会收到提示。
无论如何,是否有缓存凭据的信息,以便每次运行命令行时都不会提示用户?
应该注意的是,如果我不处理VssConnection,它将在下次运行时不提示。
更新 要明确的是,一旦将对象附加到VssConnection对象后创建连接,问题就不会缓存VssClientCredentials实例。问题是在程序执行之间(即在本地计算机上)缓存用户令牌,以便下次从命令行执行实用程序时,用户不必再次键入其凭据。类似于每次启动时不必始终登录Visual Studio的方式。
因此,我找到了一个切实可行的解决方案,似乎正是我想要的。如果有更好的解决方案,请随时发布。
解决方案:由于VssClientCredentials.Storageproperty期望实现一个类IVssCredentialStorage,所以我通过从stock VssClientCredentialStorage类派生了一个实现该接口的类。
然后,它将基于与令牌一起存储在注册表中的过期租约覆盖围绕检索和删除令牌来管理令牌的方法。
如果检索到令牌并具有过期的租约,则将令牌从存储中删除并返回null,并且VssConnection该类显示一个UI,强制用户输入其凭据。如果令牌未过期,则不会提示用户,并且将使用缓存的凭据。
现在,我可以执行以下操作:
现在,我在实用程序中内置了标准的租约到期时间,但用户可以使用命令行选项对其进行更改。用户也可以清除缓存的凭据。
密钥在RemoveToken覆盖中。对基类的调用是将其从注册表中删除的方法,因此,如果绕过该基类(对于我来说,如果租约尚未到期),则将保留注册表项。这使VssConnection可以使用缓存的凭据,而不必在每次执行程序时提示用户!
调用代码示例:
public static VssConnection CreateConnection(Uri url, VssCredentials credentials = null, double tokenLeaseInSeconds = VssClientCredentialCachingStorage.DefaultTokenLeaseInSeconds)
{
credentials = credentials ?? new VssClientCredentials();
credentials.Storage = GetVssClientCredentialStorage(tokenLeaseInSeconds);
var connection = new VssConnection(url, credentials);
connection.ConnectAsync().SyncResult();
return connection;
}
private static VssClientCredentialCachingStorage GetVssClientCredentialStorage(double tokenLeaseInSeconds)
{
return new VssClientCredentialCachingStorage("YourApp", "YourNamespace", tokenLeaseInSeconds);
}
Run Code Online (Sandbox Code Playgroud)
派生的存储类:
/// <summary>
/// Class to alter the credential storage behavior to allow the token to be cached between sessions.
/// </summary>
/// <seealso cref="Microsoft.VisualStudio.Services.Common.IVssCredentialStorage" />
public class VssClientCredentialCachingStorage : VssClientCredentialStorage
{
#region [Private]
private const string __tokenExpirationKey = "ExpirationDateTime";
private double _tokenLeaseInSeconds;
#endregion [Private]
/// <summary>
/// The default token lease in seconds
/// </summary>
public const double DefaultTokenLeaseInSeconds = 86400;// one day
/// <summary>
/// Initializes a new instance of the <see cref="VssClientCredentialCachingStorage"/> class.
/// </summary>
/// <param name="storageKind">Kind of the storage.</param>
/// <param name="storageNamespace">The storage namespace.</param>
/// <param name="tokenLeaseInSeconds">The token lease in seconds.</param>
public VssClientCredentialCachingStorage(string storageKind = "VssApp", string storageNamespace = "VisualStudio", double tokenLeaseInSeconds = DefaultTokenLeaseInSeconds)
: base(storageKind, storageNamespace)
{
this._tokenLeaseInSeconds = tokenLeaseInSeconds;
}
/// <summary>
/// Removes the token.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="token">The token.</param>
public override void RemoveToken(Uri serverUrl, IssuedToken token)
{
this.RemoveToken(serverUrl, token, false);
}
/// <summary>
/// Removes the token.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="token">The token.</param>
/// <param name="force">if set to <c>true</c> force the removal of the token.</param>
public void RemoveToken(Uri serverUrl, IssuedToken token, bool force)
{
//////////////////////////////////////////////////////////
// Bypassing this allows the token to be stored in local
// cache. Token is removed if lease is expired.
if (force || token != null && this.IsTokenExpired(token))
base.RemoveToken(serverUrl, token);
//////////////////////////////////////////////////////////
}
/// <summary>
/// Retrieves the token.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="credentialsType">Type of the credentials.</param>
/// <returns>The <see cref="IssuedToken"/></returns>
public override IssuedToken RetrieveToken(Uri serverUrl, VssCredentialsType credentialsType)
{
var token = base.RetrieveToken(serverUrl, credentialsType);
if (token != null)
{
bool expireToken = this.IsTokenExpired(token);
if (expireToken)
{
base.RemoveToken(serverUrl, token);
token = null;
}
else
{
// if retrieving the token before it is expired,
// refresh the lease period.
this.RefreshLeaseAndStoreToken(serverUrl, token);
token = base.RetrieveToken(serverUrl, credentialsType);
}
}
return token;
}
/// <summary>
/// Stores the token.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="token">The token.</param>
public override void StoreToken(Uri serverUrl, IssuedToken token)
{
this.RefreshLeaseAndStoreToken(serverUrl, token);
}
/// <summary>
/// Clears all tokens.
/// </summary>
/// <param name="url">The URL.</param>
public void ClearAllTokens(Uri url = null)
{
IEnumerable<VssToken> tokens = this.TokenStorage.RetrieveAll(base.TokenKind).ToList();
if (url != default(Uri))
tokens = tokens.Where(t => StringComparer.InvariantCultureIgnoreCase.Compare(t.Resource, url.ToString().TrimEnd('/')) == 0);
foreach(var token in tokens)
this.TokenStorage.Remove(token);
}
private void RefreshLeaseAndStoreToken(Uri serverUrl, IssuedToken token)
{
if (token.Properties == null)
token.Properties = new Dictionary<string, string>();
token.Properties[__tokenExpirationKey] = JsonSerializer.SerializeObject(this.GetNewExpirationDateTime());
base.StoreToken(serverUrl, token);
}
private DateTime GetNewExpirationDateTime()
{
var now = DateTime.Now;
// Ensure we don't overflow the max DateTime value
var lease = Math.Min((DateTime.MaxValue - now.Add(TimeSpan.FromSeconds(1))).TotalSeconds, this._tokenLeaseInSeconds);
// ensure we don't have negative leases
lease = Math.Max(lease, 0);
return now.AddSeconds(lease);
}
private bool IsTokenExpired(IssuedToken token)
{
bool expireToken = true;
if (token != null && token.Properties.ContainsKey(__tokenExpirationKey))
{
string expirationDateTimeJson = token.Properties[__tokenExpirationKey];
try
{
DateTime expiration = JsonSerializer.DeserializeObject<DateTime>(expirationDateTimeJson);
expireToken = DateTime.Compare(DateTime.Now, expiration) >= 0;
}
catch { }
}
return expireToken;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2096 次 |
| 最近记录: |