我遇到了一个问题,即一个应用程序尝试使用不同的身份验证方法从同一服务器访问资源,这两种方法是:
- 凭据(NTLM、Basic等)
- OAuth(Bearer)
设置 HttpBaseProtocolFilter
HttpBaseProtocolFilter
被设置为:
- 禁用缓存
- 禁用自动弹出 UI 凭据请求框
代码:
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
filter.AllowUI = false;
添加服务器凭据
如果资源需要凭据,我会使用:
filter.ServerCredential = new PasswordCredential(
RequestUri.ToString(),
UserName,
Password);
HttpClient httpClient = new HttpClient(filter);
添加OAuth Token
如果资源需要使用Bearer token,我会使用以下方法:
HttpClient httpClient = new HttpClient(filter);
httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", token);
服务器凭据为null
filter.ServerCredential = null
从服务器获得响应
using(httpClient)
{
using(HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(method), RequestUri))
{
using(HttpResponseMessage response = await httpClient.SendRequestAsync(requestMessage))
{
// Do something with response
}
}
}
问题
如果使用ServerCredential
的HttpClient
请求返回200(OK),那么即使Bearer
令牌无效且filter.ServerCredential
为空,每个后续的Bearer
请求也会返回200(OK)。
看起来filter.ServerCredential
被缓存了,所有后续的调用都是使用缓存凭据进行身份验证。
我必须重新启动应用程序才能进行Bearer
身份验证。
如何删除、禁用或清除Windows.Web.Http.HttpClient的ServerCredential
?
我尝试过的事情:
删除所有cookie
var cookieManager = filter.CookieManager;
HttpCookieCollection myCookieJar = cookieManager.GetCookies(RequestUri);
foreach (HttpCookie cookie in myCookieJar)
{
cookieManager.DeleteCookie(cookie);
}
myCookieJar
是空的。
与 PasswordCredentialPropertyStore
有关的一些内容。
Windows.Security.Credentials.PasswordCredentialPropertyStore credentialPropertyStore = new Windows.Security.Credentials.PasswordCredentialPropertyStore();
credentialPropertyStore
是空的。
而且,PasswordCredentialPropertyStore
的方法 Clear 已被保留供内部使用,不应在你的代码中使用。
有什么想法吗?
HttpClient
并将其放在using
块中进行关闭。当然,这只是一种解决方法。 - Vitor Canovatry { var credentials = _vault.FindAllByResource(PasswordVault); foreach(var passwordCredential in credentials) { _vault.Remove(passwordCredential); } } catch { // ignored }
- Ahmed Rashad MohamedSystem.Net.Http
吗? - kiewicWebView
集成,那么这不是一个选项。 - kiewic